diff --git a/docs/AlarmClientDiscovery.md b/docs/AlarmClientDiscovery.md
index 855e3dc9..16212bf9 100644
--- a/docs/AlarmClientDiscovery.md
+++ b/docs/AlarmClientDiscovery.md
@@ -909,10 +909,11 @@ Galaxy's last deploy time (`GetLastDeployTimeAsync`), so an undeployed galaxy
costs one deploy-time query per refresh rather than the alarm-attribute query
and a rebuilt list; a failed discovery or an unknown deploy time is not cached.
The gateway compares a SHA-256 of a canonical fingerprint of all six target
-fields and sends `UpdateAlarmWatchListCommand` only for a material change. The worker constructs,
-subscribes, and attaches the replacement standby on its STA before swapping it
-in; a setup failure leaves the previous standby and the current primary/subtag
-mode unchanged. The gateway advances its acknowledged fingerprint only after an
+fields and sends `UpdateAlarmWatchListCommand` only for a material change. The worker applies
+the new list to its existing subtag standby as a diff on its STA — advising only
+added alarms' subtags, unadvising only removed ones, and keeping the state of
+unchanged alarms; a failure leaves the previous list in force and the current
+primary/subtag mode unchanged. The gateway advances its acknowledged fingerprint only after an
OK reply, so a rejected update remains degraded and is retried.
`SubscribeAlarmsCommand.fallback_enabled` distinguishes an initially empty but
diff --git a/docs/Contracts.md b/docs/Contracts.md
index 12ec8736..d96f75f0 100644
--- a/docs/Contracts.md
+++ b/docs/Contracts.md
@@ -45,9 +45,11 @@ The shared alarm command model includes `SubscribeAlarms` and
initial watch list explicitly fallback-capable, allowing discovery recovery to
populate a standby without restarting the primary alarm-manager subscription.
`UpdateAlarmWatchListCommand.watch_list` is the complete replacement list. The
-worker prepares the replacement on its STA before swapping it into the existing
-failover consumer and returns a normal `MxCommandReply`; callers must treat only
-`protocol_status = OK` as acknowledgement of the new list.
+worker applies it to the existing failover consumer's standby as a diff on its
+STA (advising added alarms, unadvising removed ones, keeping unchanged alarms'
+state) and returns a normal `MxCommandReply`; a failed update leaves the previous
+list in force. Callers must treat only `protocol_status = OK` as acknowledgement
+of the new list.
`AcknowledgeAlarmRequest` carries the operator's identity: `operator_user`
(required), `operator_password` (field 6) and `operator_domain` (field 7). The
diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md
index 3d1be6d9..eabdbcac 100644
--- a/docs/MxAccessWorkerInstanceDesign.md
+++ b/docs/MxAccessWorkerInstanceDesign.md
@@ -459,14 +459,30 @@ its entry.
## Live alarm watch-list replacement
An auto-mode `SubscribeAlarms` with `fallback_enabled = true` always builds a
-`FailoverAlarmConsumer`, even when initial discovery supplied no targets. The
-handler retains the subscription expression so `UpdateAlarmWatchList` can build
-and subscribe a new subtag consumer entirely on the session STA. The failover
-consumer attaches the replacement's transition callback before swapping the
-standby reference, then detaches and disposes the old standby. If construction,
-subscription, or attachment fails, it disposes the replacement and preserves
-the old standby. The active-provider selector is never reset, so primary mode
-stays primary and subtag mode immediately delegates to the new standby.
+`FailoverAlarmConsumer`, even when initial discovery supplied no targets.
+`UpdateAlarmWatchList` runs entirely on the session STA and applies the new list
+to the existing `SubtagAlarmConsumer` as a diff (MXA-010): the subtags of added
+alarms are advised on the standby's existing `LmxSubtagAlarmSource`, the subtags
+of removed alarms are unadvised (`UnAdvise` + `RemoveItem`), and an alarm whose
+target is unchanged in every field keeps its advice and its tracked state, so no
+transition is re-emitted for it. Rebuilding the standby instead cost a second
+MXAccess registration and an `AddItem`/`Advise` for every watched subtag on each
+change, however small. An alarm whose target changed is treated as removed and
+re-added and starts from fresh state; when its subtags are already advised, the
+consumer initialises it from the last value delivered for each subtag (acked and
+priority before active, so an already-acknowledged alarm syncs as `ACK_ALM`)
+rather than re-advising.
+
+The update is all-or-nothing. The new list is validated and the added subtags
+are advised before anything is swapped; if advising fails, the subtags the call
+added are unadvised again, the standby keeps serving the previous list, and the
+command fails. Unadvising removed subtags happens after the swap and is best
+effort, because an unbound subtag's callbacks are already ignored. A standby that
+is not a `SubtagAlarmConsumer` (a test seam) is still rebuilt: the handler
+retains the subscription expression, builds and subscribes a replacement, and the
+failover consumer attaches its transition callback before swapping it in and
+disposing the old one. Either way the active-provider selector is never reset, so
+primary mode stays primary and subtag mode keeps delegating to the standby.
## COM Creation
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandHandlerTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandHandlerTests.cs
index 1a642c81..1ec624aa 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandHandlerTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandHandlerTests.cs
@@ -868,6 +868,15 @@ public sealed class AlarmCommandHandlerTests
}
}
+ ///
+ public void Unadvise(IReadOnlyCollection itemAddresses)
+ {
+ foreach (string address in itemAddresses)
+ {
+ Advised.Remove(address);
+ }
+ }
+
///
public void Dispose() => Disposed = true;
}
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/FailoverAlarmConsumerTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/FailoverAlarmConsumerTests.cs
index 6eb593c6..a37c67e6 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/FailoverAlarmConsumerTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/FailoverAlarmConsumerTests.cs
@@ -239,6 +239,66 @@ public sealed class FailoverAlarmConsumerTests
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
}
+ ///
+ /// MXA-010: while failed over, an in-place watch-list update on the subtag standby keeps
+ /// subtag mode, and the added alarm's transitions are forwarded from the same standby. A
+ /// standby that is not a subtag consumer reports that it needs a rebuild instead.
+ ///
+ [Fact]
+ public void TryUpdateStandbyWatchList_WhileFailedOver_UpdatesSubtagStandbyInPlaceAndKeepsMode()
+ {
+ FlakyPrimary primary = new FlakyPrimary();
+ RaisingSubtagSource source = new RaisingSubtagSource();
+ SubtagAlarmConsumer standby = new SubtagAlarmConsumer(source, new[] { SubtagTarget("Tank01") });
+ FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 3);
+ using FailoverAlarmConsumer sut = new FailoverAlarmConsumer(primary, standby, settings);
+ FailOverAfterHealthySubscribe(sut, primary);
+ List forwarded = new List();
+ sut.AlarmTransitionEmitted += (_, e) => forwarded.Add(e);
+
+ Assert.True(sut.TryUpdateStandbyWatchList(new[] { SubtagTarget("Tank01"), SubtagTarget("Tank02") }));
+
+ Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
+ source.Raise("Tank02.Alarm.InAlarm", true);
+ Assert.Equal(MxAlarmStateKind.UnackAlm, Assert.Single(forwarded).Record.State);
+
+ using FailoverAlarmConsumer stubbed = new FailoverAlarmConsumer(new FlakyPrimary(), new StubStandby(), settings);
+ Assert.False(stubbed.TryUpdateStandbyWatchList(new[] { SubtagTarget("Tank01") }));
+ }
+
+ private static AlarmSubtagTarget SubtagTarget(string tank) => new AlarmSubtagTarget
+ {
+ AlarmFullReference = $"Galaxy!Area.{tank}.Alarm",
+ SourceObjectReference = tank,
+ ActiveSubtag = $"{tank}.Alarm.InAlarm",
+ AckedSubtag = $"{tank}.Alarm.Acked",
+ AckCommentSubtag = $"{tank}.Alarm.AckMsg",
+ };
+
+ private sealed class RaisingSubtagSource : ISubtagAlarmSource
+ {
+ public event EventHandler? ValueChanged;
+
+ public void Advise(IReadOnlyCollection itemAddresses)
+ {
+ }
+
+ public void Unadvise(IReadOnlyCollection itemAddresses)
+ {
+ }
+
+ public void Raise(string address, object value) => ValueChanged?.Invoke(this, new SubtagValueChange
+ {
+ ItemAddress = address,
+ Value = value,
+ TimestampUtc = DateTime.UtcNow,
+ });
+
+ public void Dispose()
+ {
+ }
+ }
+
///
/// MXA-001: a primary whose Subscribe failed, and whose PollOnce is then a
/// silent no-op (the wnwrap shape), must still count as failing, so the
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs
index b550b104..f07bfa1c 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs
@@ -136,6 +136,61 @@ public sealed class LmxSubtagAlarmSourceTests
Assert.Empty(server.Writes);
}
+ ///
+ /// MXA-010: tears down only the named items
+ /// (UnAdvise then RemoveItem), skips addresses it never advised, stops raising for the
+ /// removed handle, and leaves the server registered for the items that remain.
+ ///
+ [Fact]
+ public void Unadvise_RemovesOnlyNamedItemsAndStopsTheirCallbacks()
+ {
+ var server = new RecordingMxAccessServer();
+ using var source = new LmxSubtagAlarmSource(server, FakeServerHandle);
+ source.Advise(new[] { "Tank1.Alarm.Subtag", "Tank2.Alarm.Subtag" });
+ int removedHandle = server.LastItemHandleFor("Tank1.Alarm.Subtag");
+ int keptHandle = server.LastItemHandleFor("Tank2.Alarm.Subtag");
+ List raised = new List();
+ source.ValueChanged += (_, change) => raised.Add(change.ItemAddress);
+
+ source.Unadvise(new[] { "Tank1.Alarm.Subtag", "Never.Advised" });
+
+ Assert.Equal(new[] { removedHandle }, server.UnAdvisedItemHandles);
+ Assert.Equal(new[] { removedHandle }, server.RemovedItemHandles);
+ Assert.Equal(0, server.UnregisterCount);
+
+ source.HandleDataChange(removedHandle, pvItemValue: true, pftItemTimeStamp: null);
+ source.HandleDataChange(keptHandle, pvItemValue: true, pftItemTimeStamp: null);
+ Assert.Equal(new[] { "Tank2.Alarm.Subtag" }, raised);
+
+ // A removed address can be advised again, on a new item.
+ source.Advise(new[] { "Tank1.Alarm.Subtag" });
+ Assert.Equal(3, server.AdviseCount);
+ Assert.NotEqual(removedHandle, server.LastItemHandleFor("Tank1.Alarm.Subtag"));
+ }
+
+ ///
+ /// An item whose Advise failed after AddItem stays known to the source: a retried Advise
+ /// finishes advising it instead of skipping it, and Unadvise removes it rather than leaving
+ /// it orphaned on the server.
+ ///
+ [Fact]
+ public void Advise_FailureAfterAddItem_IsRetriedAndRemovable()
+ {
+ var server = new RecordingMxAccessServer { FailAdviseCalls = 1 };
+ using var source = new LmxSubtagAlarmSource(server, FakeServerHandle);
+
+ Assert.Throws(
+ () => source.Advise(new[] { "Tank1.Alarm.Subtag" }));
+ int handle = server.LastItemHandleFor("Tank1.Alarm.Subtag");
+
+ source.Advise(new[] { "Tank1.Alarm.Subtag" });
+ Assert.Single(server.AddedItems);
+ Assert.Equal(1, server.AdviseCount);
+
+ source.Unadvise(new[] { "Tank1.Alarm.Subtag" });
+ Assert.Equal(new[] { handle }, server.RemovedItemHandles);
+ }
+
///
/// Verifies is idempotent: a
/// second call performs no further teardown.
@@ -217,9 +272,18 @@ public sealed class LmxSubtagAlarmSourceTests
///
public void RemoveItem(int serverHandle, int itemHandle) => RemovedItemHandles.Add(itemHandle);
+ /// Gets or sets how many upcoming calls throw a COM failure.
+ public int FailAdviseCalls { get; set; }
+
///
public void Advise(int serverHandle, int itemHandle)
{
+ if (FailAdviseCalls > 0)
+ {
+ FailAdviseCalls--;
+ throw new System.Runtime.InteropServices.COMException("simulated Advise failure", unchecked((int)0x80004005));
+ }
+
AdviseCount++;
AdvisedServerHandles.Add(serverHandle);
}
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/SubtagAlarmConsumerTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/SubtagAlarmConsumerTests.cs
index 76b1be21..1b08f5d0 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/SubtagAlarmConsumerTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/SubtagAlarmConsumerTests.cs
@@ -243,6 +243,150 @@ public sealed class SubtagAlarmConsumerTests
Assert.Equal(AlarmAckOutcome.AlarmNotFound, consumer.ResolveAckTarget(Guid.NewGuid()).Failure);
}
+ private static AlarmSubtagTarget Target(string tank, string ackSuffix = "AckMsg") => new AlarmSubtagTarget
+ {
+ AlarmFullReference = $"Galaxy!TestArea.{tank}.Level.HiHi",
+ SourceObjectReference = tank,
+ ActiveSubtag = $"{tank}.Level.HiHi.InAlarm",
+ AckedSubtag = $"{tank}.Level.HiHi.Acked",
+ AckCommentSubtag = $"{tank}.Level.HiHi.{ackSuffix}",
+ };
+
+ private static readonly DateTime T0 = new DateTime(2026, 12, 3, 10, 0, 0, DateTimeKind.Utc);
+
+ ///
+ /// MXA-010: a watch-list update advises only the added alarm's subtags and unadvises only
+ /// the removed alarm's; the alarm present in both lists is not touched.
+ ///
+ [Fact]
+ public void UpdateWatchList_AdvisesAddedAndUnadvisesRemovedOnly()
+ {
+ FakeSource source = new FakeSource();
+ using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01"), Target("Tank02") });
+ consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
+ source.Advised.Clear();
+
+ consumer.UpdateWatchList(new[] { Target("Tank02"), Target("Tank03") });
+
+ Assert.Equal(new[] { "Tank03.Level.HiHi.InAlarm", "Tank03.Level.HiHi.Acked" }, source.Advised);
+ Assert.Equal(new[] { "Tank01.Level.HiHi.InAlarm", "Tank01.Level.HiHi.Acked" }, source.Unadvised);
+ Assert.False(consumer.ResolveAckTargetByName("Tank01.Level.HiHi", "Galaxy", "TestArea").Found);
+ Assert.True(consumer.ResolveAckTargetByName("Tank03.Level.HiHi", "Galaxy", "TestArea").Found);
+ }
+
+ ///
+ /// An alarm whose target is unchanged keeps its state across the update: no transition is
+ /// re-emitted for it, it stays in the snapshot, and its acknowledged-during-episode latch
+ /// still yields ACK_RTN on clear.
+ ///
+ [Fact]
+ public void UpdateWatchList_UnchangedAlarm_KeepsStateWithoutReemitting()
+ {
+ FakeSource source = new FakeSource();
+ using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
+ consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
+ source.Raise("Tank01.Level.HiHi.InAlarm", true, T0);
+ source.Raise("Tank01.Level.HiHi.Acked", true, T0);
+ List emitted = new List();
+ consumer.AlarmTransitionEmitted += (_, e) => emitted.Add(e);
+
+ consumer.UpdateWatchList(new[] { Target("Tank01"), Target("Tank02") });
+
+ Assert.Empty(emitted);
+ MxAlarmSnapshotRecord active = Assert.Single(consumer.SnapshotActiveAlarms(out _));
+ Assert.Equal(MxAlarmStateKind.AckAlm, active.State);
+
+ source.Raise("Tank01.Level.HiHi.Acked", false, T0.AddSeconds(1));
+ source.Raise("Tank01.Level.HiHi.InAlarm", false, T0.AddSeconds(2));
+ Assert.Equal(MxAlarmStateKind.AckRtn, Assert.Single(emitted).Record.State);
+ }
+
+ ///
+ /// An alarm whose target changed starts from fresh state, initialised from the last value
+ /// already delivered for its still-advised subtags (the initial sync an Advise would give),
+ /// without re-advising them; the new ack-comment subtag is what acks resolve to.
+ ///
+ [Fact]
+ public void UpdateWatchList_ChangedTarget_ReinitialisesFromLastDeliveredValues()
+ {
+ FakeSource source = new FakeSource();
+ using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
+ consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
+ source.Raise("Tank01.Level.HiHi.Acked", true, T0);
+ source.Raise("Tank01.Level.HiHi.InAlarm", true, T0);
+ source.Advised.Clear();
+ List emitted = new List();
+ consumer.AlarmTransitionEmitted += (_, e) => emitted.Add(e);
+
+ consumer.UpdateWatchList(new[] { Target("Tank01", ackSuffix: "AckComment") });
+
+ Assert.Empty(source.Advised);
+ Assert.Empty(source.Unadvised);
+ // MXA-007: the buffered ack replayed before .active keeps the alarm acknowledged.
+ Assert.Equal(MxAlarmStateKind.AckAlm, Assert.Single(emitted).Record.State);
+ Assert.Equal(
+ "Tank01.Level.HiHi.AckComment",
+ consumer.ResolveAckTargetByName("Tank01.Level.HiHi", "Galaxy", "TestArea").ItemAddress);
+ }
+
+ ///
+ /// MXA-005 holds across the replay: a fresh alarm whose last delivered .active update had
+ /// bad quality is not initialised from it.
+ ///
+ [Fact]
+ public void UpdateWatchList_ChangedTarget_DoesNotReplayBadQualityValue()
+ {
+ FakeSource source = new FakeSource();
+ using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
+ consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
+ source.Raise("Tank01.Level.HiHi.InAlarm", true, T0, quality: 0x04);
+
+ consumer.UpdateWatchList(new[] { Target("Tank01", ackSuffix: "AckComment") });
+
+ Assert.Empty(consumer.SnapshotActiveAlarms(out _));
+ }
+
+ ///
+ /// A failed advise rolls the update back: the subtags it added are unadvised again and the
+ /// consumer keeps serving the previous list, state included.
+ ///
+ [Fact]
+ public void UpdateWatchList_AdviseFails_RollsBackToPreviousList()
+ {
+ FakeSource source = new FakeSource();
+ using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
+ consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
+ source.Raise("Tank01.Level.HiHi.InAlarm", true, T0);
+ source.FailAdviseOf = "Tank03.Level.HiHi.InAlarm";
+
+ Assert.Throws(
+ () => consumer.UpdateWatchList(new[] { Target("Tank02"), Target("Tank03") }));
+
+ Assert.Equal(
+ new[] { "Tank02.Level.HiHi.InAlarm", "Tank02.Level.HiHi.Acked", "Tank03.Level.HiHi.InAlarm", "Tank03.Level.HiHi.Acked" },
+ source.Unadvised);
+ Assert.True(consumer.ResolveAckTargetByName("Tank01.Level.HiHi", "Galaxy", "TestArea").Found);
+ Assert.False(consumer.ResolveAckTargetByName("Tank02.Level.HiHi", "Galaxy", "TestArea").Found);
+ Assert.Single(consumer.SnapshotActiveAlarms(out _));
+ }
+
+ /// A list that repeats an alarm reference is rejected before the source is touched.
+ [Fact]
+ public void UpdateWatchList_DuplicateReference_ThrowsWithoutTouchingSource()
+ {
+ FakeSource source = new FakeSource();
+ using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
+ consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
+ source.Advised.Clear();
+
+ Assert.Throws(
+ () => consumer.UpdateWatchList(new[] { Target("Tank02"), Target("Tank02") }));
+
+ Assert.Empty(source.Advised);
+ Assert.Empty(source.Unadvised);
+ Assert.True(consumer.ResolveAckTargetByName("Tank01.Level.HiHi", "Galaxy", "TestArea").Found);
+ }
+
private sealed class FakeSource : ISubtagAlarmSource
{
/// Raised when an advised subtag reports a new value.
@@ -251,23 +395,45 @@ public sealed class SubtagAlarmConsumerTests
/// Gets the subtag addresses passed to .
public List Advised { get; } = new List();
+ /// Gets the subtag addresses passed to .
+ public List Unadvised { get; } = new List();
+
+ /// Gets or sets an address whose advise throws (after the addresses before it were advised).
+ public string? FailAdviseOf { get; set; }
+
///
public void Advise(IReadOnlyCollection itemAddresses)
{
- Advised.AddRange(itemAddresses);
+ foreach (string address in itemAddresses)
+ {
+ if (address == FailAdviseOf)
+ {
+ throw new System.Runtime.InteropServices.COMException("simulated AddItem failure", unchecked((int)0x80004005));
+ }
+
+ Advised.Add(address);
+ }
+ }
+
+ ///
+ public void Unadvise(IReadOnlyCollection itemAddresses)
+ {
+ Unadvised.AddRange(itemAddresses);
}
/// Raises a for the given subtag.
/// The subtag address whose value changed.
/// The new value.
/// The UTC timestamp of the change.
- public void Raise(string address, object? value, DateTime timestampUtc)
+ /// The item quality, or null when not reported.
+ public void Raise(string address, object? value, DateTime timestampUtc, int? quality = null)
{
ValueChanged?.Invoke(this, new SubtagValueChange
{
ItemAddress = address,
Value = value,
TimestampUtc = timestampUtc,
+ Quality = quality,
});
}
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmCommandHandler.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmCommandHandler.cs
index 39632734..ba0cf50b 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmCommandHandler.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmCommandHandler.cs
@@ -296,6 +296,14 @@ public sealed class AlarmCommandHandler : IAlarmCommandHandler
"UpdateAlarmWatchList requires an active fallback-capable alarm subscription.");
}
+ // The subtag standby takes the new list as a diff: only added and removed alarms cost
+ // COM calls, and unchanged alarms keep their state (MXA-010). Any other standby is
+ // rebuilt and swapped.
+ if (failoverConsumer.TryUpdateStandbyWatchList(watchList))
+ {
+ return;
+ }
+
IMxAccessAlarmConsumer replacement = BuildStandby(watchList);
failoverConsumer.ReplaceStandby(replacement, subscriptionExpression);
}
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/FailoverAlarmConsumer.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/FailoverAlarmConsumer.cs
index c290f292..100b0e9a 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/FailoverAlarmConsumer.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/FailoverAlarmConsumer.cs
@@ -169,6 +169,32 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
try { previous.Dispose(); } catch { /* replacement is already active */ }
}
+ ///
+ /// Applies a replacement watch list to the current standby in place when the standby is a
+ /// , which advises only the added subtags and unadvises
+ /// only the removed ones instead of being rebuilt (MXA-010). A failure leaves the standby
+ /// serving its previous list. The active-provider selector is untouched either way.
+ ///
+ /// The complete replacement watch list.
+ ///
+ /// when the standby was updated in place;
+ /// when it cannot be, and the caller must build a replacement for
+ /// .
+ ///
+ public bool TryUpdateStandbyWatchList(IReadOnlyList watchList)
+ {
+ if (disposed) throw new ObjectDisposedException(nameof(FailoverAlarmConsumer));
+ if (watchList is null) throw new ArgumentNullException(nameof(watchList));
+
+ if (standby is not SubtagAlarmConsumer subtagStandby)
+ {
+ return false;
+ }
+
+ subtagStandby.UpdateWatchList(watchList);
+ return true;
+ }
+
///
public void Subscribe(string subscription)
{
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/ISubtagAlarmSource.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/ISubtagAlarmSource.cs
index ef160c26..802d0ded 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/ISubtagAlarmSource.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/ISubtagAlarmSource.cs
@@ -16,4 +16,13 @@ public interface ISubtagAlarmSource : IDisposable
/// Begins advising the supplied MXAccess subtag item addresses.
/// The subtag references to advise.
void Advise(IReadOnlyCollection itemAddresses);
+
+ ///
+ /// Stops advising the supplied subtag item addresses and drops them from the source, so
+ /// no further is raised for them. Best effort: an address that
+ /// is not advised is skipped, and a COM failure removing one address does not stop the
+ /// rest. Used to shrink a live watch list without rebuilding the source.
+ ///
+ /// The subtag references to stop advising.
+ void Unadvise(IReadOnlyCollection itemAddresses);
}
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs
index 83c3ec7f..d17a7487 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs
@@ -26,7 +26,7 @@ namespace ZB.MOM.WW.MxGateway.Worker.MxAccess;
/// Threading. The LMXProxyServerClass CLSID is
/// apartment-threaded and delivers OnDataChange via the STA
/// message pump. Every method on this type — the lazy
-/// creation and — must be
+/// creation, and — must be
/// invoked on the worker's STA that created the source, exactly as
/// and
/// require. The OnDataChange COM event also arrives on that STA.
@@ -126,16 +126,64 @@ public sealed class LmxSubtagAlarmSource : ISubtagAlarmSource
continue;
}
- if (itemHandlesByAddress.ContainsKey(itemAddress!))
+ if (itemHandlesByAddress.TryGetValue(itemAddress!, out int existingHandle))
+ {
+ // Added earlier but its Advise failed: finish advising it instead of skipping it.
+ if (!advisedItemHandles.Contains(existingHandle))
+ {
+ mxServer.Advise(serverHandle, existingHandle);
+ advisedItemHandles.Add(existingHandle);
+ }
+
+ continue;
+ }
+
+ // Track the item as soon as it is added, so an Advise failure leaves it known to
+ // Unadvise (which removes it) rather than orphaned on the server until Unregister.
+ int itemHandle = mxServer.AddItem(serverHandle, itemAddress!);
+ itemHandlesByAddress[itemAddress!] = itemHandle;
+ addressesByItemHandle[itemHandle] = itemAddress!;
+ mxServer.Advise(serverHandle, itemHandle);
+ advisedItemHandles.Add(itemHandle);
+ }
+ }
+
+ ///
+ public void Unadvise(IReadOnlyCollection itemAddresses)
+ {
+ if (itemAddresses is null)
+ {
+ throw new ArgumentNullException(nameof(itemAddresses));
+ }
+
+ ThrowIfDisposed();
+
+ IMxAccessServer? mxServer = server;
+ foreach (string? itemAddress in itemAddresses)
+ {
+ if (string.IsNullOrWhiteSpace(itemAddress)
+ || !itemHandlesByAddress.TryGetValue(itemAddress!, out int itemHandle))
{
continue;
}
- int itemHandle = mxServer.AddItem(serverHandle, itemAddress!);
- mxServer.Advise(serverHandle, itemHandle);
- itemHandlesByAddress[itemAddress!] = itemHandle;
- addressesByItemHandle[itemHandle] = itemAddress!;
- advisedItemHandles.Add(itemHandle);
+ // Drop the mapping first so a callback already queued for this handle is ignored
+ // even if the COM calls below fail.
+ itemHandlesByAddress.Remove(itemAddress!);
+ addressesByItemHandle.Remove(itemHandle);
+ bool wasAdvised = advisedItemHandles.Remove(itemHandle);
+
+ if (mxServer is null || !registered)
+ {
+ continue;
+ }
+
+ if (wasAdvised)
+ {
+ try { mxServer.UnAdvise(serverHandle, itemHandle); } catch { /* best effort */ }
+ }
+
+ try { mxServer.RemoveItem(serverHandle, itemHandle); } catch { /* best effort */ }
}
}
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmConsumer.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmConsumer.cs
index 9418ead4..f0df5965 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmConsumer.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmConsumer.cs
@@ -37,10 +37,18 @@ namespace ZB.MOM.WW.MxGateway.Worker.MxAccess;
public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
{
private readonly ISubtagAlarmSource source;
- private readonly SubtagAlarmStateMachine stateMachine;
- private readonly Dictionary targetsByReference;
- private readonly Dictionary referencesBySyntheticGuid;
private readonly EventHandler valueChangedHandler;
+
+ // The most recent change per advised address. A watch-list update that re-binds an already
+ // advised address to a fresh alarm state replays it instead of re-advising the subtag: MXAccess
+ // delivers a subtag's current value once, on Advise, so a fresh state would otherwise wait for
+ // the next real change to learn it.
+ private readonly Dictionary lastChangeByAddress =
+ new Dictionary(StringComparer.OrdinalIgnoreCase);
+
+ private SubtagAlarmStateMachine stateMachine;
+ private Dictionary targetsByReference;
+ private Dictionary referencesBySyntheticGuid;
private bool subscribed;
private bool disposed;
@@ -66,16 +74,7 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
}
this.stateMachine = new SubtagAlarmStateMachine(watchList);
- this.targetsByReference = new Dictionary(StringComparer.OrdinalIgnoreCase);
- this.referencesBySyntheticGuid = new Dictionary();
-
- foreach (AlarmSubtagTarget target in watchList)
- {
- string reference = target.AlarmFullReference ?? string.Empty;
- this.targetsByReference[reference] = target;
- this.referencesBySyntheticGuid[SyntheticAlarmGuid.ForReference(reference)] = reference;
- }
-
+ BuildTargetMaps(watchList, out this.targetsByReference, out this.referencesBySyntheticGuid);
this.valueChangedHandler = OnValueChanged;
}
@@ -104,6 +103,121 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
}
}
+ ///
+ /// Replaces the watch list in place, applying only the difference to the subtag source:
+ /// subtags of added alarms are advised, subtags of removed alarms are unadvised, and an alarm
+ /// whose target is unchanged keeps both its advice and its tracked state (MXA-010). An alarm
+ /// whose target changed in any field is treated as removed and re-added, starting from fresh
+ /// state.
+ ///
+ ///
+ ///
+ /// The update is all-or-nothing from the caller's view. The new list is validated (a
+ /// duplicate reference or subtag address throws) and the added subtags are advised before
+ /// anything is swapped; if advising fails, the subtags this call added are unadvised again
+ /// and the consumer keeps serving the previous list. Unadvising removed subtags happens
+ /// after the swap and is best effort, because a removed subtag that cannot be unadvised is
+ /// already unbound and its callbacks are ignored.
+ ///
+ ///
+ /// An alarm whose state is fresh but whose subtag was already advised (its target changed,
+ /// or the address moved to another alarm) is initialised from the last value delivered for
+ /// that subtag, the same initial sync an Advise would deliver. Transitions this produces
+ /// are emitted like any other. Before the list is only recorded;
+ /// advises it.
+ ///
+ ///
+ /// The complete replacement watch list.
+ /// is .
+ /// The list repeats an alarm reference or a subtag address.
+ public void UpdateWatchList(IReadOnlyList watchList)
+ {
+ if (disposed)
+ {
+ throw new ObjectDisposedException(nameof(SubtagAlarmConsumer));
+ }
+
+ if (watchList is null)
+ {
+ throw new ArgumentNullException(nameof(watchList));
+ }
+
+ SubtagAlarmStateMachine previous = stateMachine;
+ SubtagAlarmStateMachine next = new SubtagAlarmStateMachine(watchList, previous);
+ BuildTargetMaps(
+ watchList,
+ out Dictionary nextTargets,
+ out Dictionary nextGuids);
+
+ List toAdvise = new List();
+ foreach (string address in next.BoundAddresses)
+ {
+ if (!previous.IsBound(address))
+ {
+ toAdvise.Add(address);
+ }
+ }
+
+ List toUnadvise = new List();
+ foreach (string address in previous.BoundAddresses)
+ {
+ if (!next.IsBound(address))
+ {
+ toUnadvise.Add(address);
+ }
+ }
+
+ if (subscribed && toAdvise.Count > 0)
+ {
+ try
+ {
+ source.Advise(toAdvise);
+ }
+ catch
+ {
+ // Roll back what this call added so the source again matches the list still in
+ // force. None of these addresses is bound in the previous list, so nothing it
+ // still serves is touched.
+ try { source.Unadvise(toAdvise); } catch { /* best effort — preserve the advise failure */ }
+ foreach (string address in toAdvise)
+ {
+ lastChangeByAddress.Remove(address);
+ }
+
+ throw;
+ }
+ }
+
+ stateMachine = next;
+ targetsByReference = nextTargets;
+ referencesBySyntheticGuid = nextGuids;
+
+ if (!subscribed)
+ {
+ return;
+ }
+
+ if (toUnadvise.Count > 0)
+ {
+ try { source.Unadvise(toUnadvise); } catch { /* best effort — the addresses are already unbound */ }
+ foreach (string address in toUnadvise)
+ {
+ lastChangeByAddress.Remove(address);
+ }
+ }
+
+ // Initial sync for alarms that start fresh on an address whose value already arrived —
+ // either advised under the previous list, or delivered re-entrantly while Advise ran
+ // above, when the previous machine had no binding for it yet.
+ foreach (string address in next.FreshAddresses)
+ {
+ if (lastChangeByAddress.TryGetValue(address, out SubtagValueChange change))
+ {
+ ApplyAndEmit(change);
+ }
+ }
+ }
+
///
public AlarmAckTarget ResolveAckTarget(Guid alarmGuid)
{
@@ -164,6 +278,7 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
}
disposed = true;
+ lastChangeByAddress.Clear();
if (subscribed)
{
@@ -196,6 +311,16 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
return;
}
+ if (!string.IsNullOrEmpty(change.ItemAddress))
+ {
+ lastChangeByAddress[change.ItemAddress] = change;
+ }
+
+ ApplyAndEmit(change);
+ }
+
+ private void ApplyAndEmit(SubtagValueChange change)
+ {
IReadOnlyList transitions =
stateMachine.Apply(change.ItemAddress, change.Value, change.TimestampUtc, change.Quality);
if (transitions.Count == 0)
@@ -244,6 +369,21 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
return target;
}
+ private static void BuildTargetMaps(
+ IReadOnlyList watchList,
+ out Dictionary targets,
+ out Dictionary guids)
+ {
+ targets = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ guids = new Dictionary();
+ foreach (AlarmSubtagTarget target in watchList)
+ {
+ string reference = target.AlarmFullReference ?? string.Empty;
+ targets[reference] = target;
+ guids[SyntheticAlarmGuid.ForReference(reference)] = reference;
+ }
+ }
+
private static AlarmAckTarget ToAckTarget(AlarmSubtagTarget target)
{
string ackItem = target.AckCommentSubtag ?? string.Empty;
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmStateMachine.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmStateMachine.cs
index 84f1454f..5ebce23d 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmStateMachine.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmStateMachine.cs
@@ -31,9 +31,30 @@ public sealed class SubtagAlarmStateMachine
private readonly Dictionary _statesByReference = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary _bindingsByAddress = new(StringComparer.OrdinalIgnoreCase);
+ // Subtag addresses bound to an alarm state created by this instance rather than carried over
+ // from a previous machine; on a watch-list update these need an initial value. The .active
+ // subtags are kept apart so FreshAddresses can list them last.
+ private readonly List _freshAddresses = new();
+ private readonly List _freshActiveAddresses = new();
+
/// Initializes the machine from the configured alarm subtag targets.
/// The alarm targets whose subtags will be observed.
public SubtagAlarmStateMachine(IEnumerable targets)
+ : this(targets, carryOver: null)
+ {
+ }
+
+ ///
+ /// Initializes the machine for an updated watch list, carrying over the tracked state of
+ /// every alarm whose target is unchanged from . An alarm whose
+ /// target is new or differs in any field starts with fresh state, and its subtag addresses
+ /// are reported in . Construction validates the whole list
+ /// before anything is shared, and never modifies : a rejected
+ /// list leaves the previous machine fully usable.
+ ///
+ /// The alarm targets whose subtags will be observed.
+ /// The machine serving the previous watch list, or .
+ public SubtagAlarmStateMachine(IEnumerable targets, SubtagAlarmStateMachine? carryOver)
{
if (targets is null)
{
@@ -56,15 +77,48 @@ public sealed class SubtagAlarmStateMachine
nameof(targets));
}
- var state = new AlarmState(target);
+ // An unchanged target keeps its state object, so its active/acked/priority history
+ // survives the update and its subtags need no re-advise or re-sync. Sharing the object
+ // is safe: the previous machine is discarded once this one is committed, and until
+ // then either machine applies the same updates to it.
+ bool carried = false;
+ AlarmState? state = null;
+ if (carryOver is not null
+ && carryOver._statesByReference.TryGetValue(reference, out AlarmState previous)
+ && previous.Target.Equals(target))
+ {
+ state = previous;
+ carried = true;
+ }
+
+ state ??= new AlarmState(target);
_statesByReference[reference] = state;
- Bind(target.ActiveSubtag, state, SubtagRole.Active);
- Bind(target.AckedSubtag, state, SubtagRole.Acked);
- Bind(target.PrioritySubtag, state, SubtagRole.Priority);
+ Bind(target.ActiveSubtag, state, SubtagRole.Active, carried);
+ Bind(target.AckedSubtag, state, SubtagRole.Acked, carried);
+ Bind(target.PrioritySubtag, state, SubtagRole.Priority, carried);
}
+
+ _freshAddresses.AddRange(_freshActiveAddresses);
}
+ /// Gets the subtag addresses this machine observes (active, acked and priority).
+ public IReadOnlyCollection BoundAddresses => _bindingsByAddress.Keys;
+
+ ///
+ /// Gets the subtag addresses bound to an alarm whose state this machine created rather than
+ /// carried over — every address for a machine built without a carry-over source. Every
+ /// .active subtag comes after all .acked and .priority subtags, so
+ /// replaying known values in this order initialises each fresh alarm with one transition
+ /// that already carries its acknowledgement and priority (MXA-007).
+ ///
+ public IReadOnlyCollection FreshAddresses => _freshAddresses;
+
+ /// Returns whether is observed by this machine.
+ /// The subtag address (case-insensitive).
+ /// when the address is bound to an alarm.
+ public bool IsBound(string itemAddress) => _bindingsByAddress.ContainsKey(itemAddress);
+
///
/// Applies a single subtag value change whose quality is not reported
/// and returns any synthesized transitions. Unknown addresses and no-op
@@ -250,7 +304,7 @@ public sealed class SubtagAlarmStateMachine
};
}
- private void Bind(string? address, AlarmState state, SubtagRole role)
+ private void Bind(string? address, AlarmState state, SubtagRole role, bool carried)
{
if (!string.IsNullOrEmpty(address))
{
@@ -262,6 +316,10 @@ public sealed class SubtagAlarmStateMachine
}
_bindingsByAddress[address!] = new SubtagBinding(state, role);
+ if (!carried)
+ {
+ (role == SubtagRole.Active ? _freshActiveAddresses : _freshAddresses).Add(address!);
+ }
}
}
@@ -356,9 +414,13 @@ public sealed class SubtagAlarmStateMachine
/// The configured alarm subtag target this state tracks.
public AlarmState(AlarmSubtagTarget target)
{
+ Target = target;
(_providerName, _group, _tagName) = DeriveNameParts(target);
}
+ /// Gets the watch-list target this state was built from.
+ public AlarmSubtagTarget Target { get; }
+
/// Gets or sets whether the alarm is currently active (raised).
public bool Active { get; set; }