diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md
index 1d67c4cc3..f43bfbd00 100644
--- a/.claude/rules/drivers.md
+++ b/.claude/rules/drivers.md
@@ -276,10 +276,16 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
FOCAS's is PAUSED, its told record kept, #647) — the device-state half of `ShutdownAsync` only; the poll engine is kept and the actor re-subscribes
after every successful init. AbCip publishes fresh tag tables by reference swap (a second init used to throw
"tag name collision"); S7 swaps `Plc` under `_gate`.
-- **Data and alarm subscriptions are independent in `DriverInstanceActor` (#662):** a data re-subscribe (every
- deploy's bulk push to a kept driver) detaches DATA only (`DetachDataSubscription`) — it used to unhook
+- **Data and alarm subscriptions are independent in `DriverInstanceActor` (#662):** a data re-subscribe (a
+ deploy's bulk push to a kept driver — since #995 only when something it seeds changed, see below) detaches DATA only (`DetachDataSubscription`) — it used to unhook
`OnAlarmEvent` too, silently killing the native-alarm feed until a respawn. The health-poll reconcile
re-attaches/re-subscribes alarms as well as data, so a failed alarm subscribe is retried every tick.
+- **An untouched kept driver is not re-subscribed by a deploy (#995 R-11).** The bulk push skips a child whose
+ seeding fingerprint (value refs + each ref's raw/UNS fan-out + historization + alarm refs) is unchanged and none of
+ whose refs gained a mux consumer (VirtualTag / scripted alarm / `IDependencyConsumer` driver); skipped drivers are
+ re-pushed after the address-space outcome if it was a rebuild (`RebuildCompleted.AddressSpaceRebuilt`), degraded,
+ timed out, or the apply threw. A new mux value consumer must join `DriverHostActor.ConsumerRefs`.
+ `docs/DriverLifecycle.md` §"A deploy no longer re-subscribes an untouched driver".
- **A config change is a respawn — there is NO in-place path (#665).** The `ApplyDelta`/`ApplyResult`/`DeltaApplied`
seam (host `ApplyChildDelta`, `DriverSpawnPlan.ToApplyDelta`, the actor's Connected reinit and mid-connect
`AdoptConfigDuringInit`) was unreachable since #516 and is deleted; #663/#664 were latent bugs in it. `IDriver.ReinitializeAsync`
diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md
index 4504e752a..aeabfe69d 100644
--- a/docs/DriverLifecycle.md
+++ b/docs/DriverLifecycle.md
@@ -188,7 +188,7 @@ routes it to `Unsubscribe`, dropping a stale handle.)
| Route | Trigger | What re-provisions it |
|---|---|---|
-| **Deploy reconcile** | `ApplyDriverSpecs` → `SpawnChild` | `SpawnChild` sends `InitializeRequested` then the desired set; the apply's bulk push then sends the (freshly rebuilt) set to every child. |
+| **Deploy reconcile** | `ApplyDriverSpecs` → `SpawnChild` | `SpawnChild` sends `InitializeRequested` then the desired set; the apply's bulk push then sends the (freshly rebuilt) set to every child **that needs it** (#995, below). |
| **Operator Restart** | `/hosts` → Restart → `HandleRestartDriver` | Stops the child, respawns from the cached spec — and `SpawnChild` sends the desired set, because it always does. **This is the 03/S16 fix**: there is no bulk push on this path, and before it the respawned child subscribed to nothing until the next deployment. |
| **Supervision restart** | a child throws ⇒ Akka's **default decider** ⇒ `Restart` | `DriverInstanceActor.PostRestart` Tells the host `ReprovisionRequested`; `HandleReprovisionRequested` logs a Warning naming the crash type, re-sends `InitializeRequested` (non-stub children) and the desired set. |
| **Force Reconnect** | `/hosts` → Force Reconnect → `HandleReconnectDriver` | **Nothing — verified.** It Tells `ForceReconnect` to the *same* child actor, so the instance and its `_desiredRefs`/`_desiredAlarmRefs` survive and the reconnect's Connected entry re-applies them itself. Pinned by `Force_reconnect_keeps_the_desired_set_and_re_subscribes` so a future edit to the restart paths cannot break the one that was already correct. |
@@ -247,6 +247,23 @@ Things to know before touching any of this:
re-subscribing** so a filtering driver does not accumulate two overlapping ones. There is still
deliberately no unsubscribe-on-**empty**: a removed alarm tag's condition node is torn down on the
address-space rebuild and `ForwardNativeAlarm` drops any transition whose `ConditionId` no longer maps.
+- **A deploy no longer re-subscribes an untouched driver (#995, review 2026-12-02 R-11).** A re-subscribe tears down
+ the driver's whole data subscription (OpcUaClient monitored items, Galaxy advise through mxaccessgw, a forced
+ full re-read) and leaves a gap; on a kept driver whose set did not change its only job is **seeding** — the
+ initial values it produces give a node or consumer that is new since the last apply its first value. So the
+ deploy path (`HandleArtifactForApply` → `ApplyDesiredSubscriptions(skipUnchanged: true)`) skips a child only when
+ ALL hold: it is the child that already got a plain (non-acquisition) set from this host (`_plainPushedTo` — a
+ respawn is a new actor and is always pushed); its **seeding fingerprint** is unchanged (value refs, each ref's
+ fan-out NodeIds — raw + every referencing UNS mirror, so an added/re-pointed mirror re-pushes — its
+ historization, and the alarm refs); and none of its value refs **entered the mux-consumer set** (enabled
+ VirtualTag / scripted-alarm deps + every hosted `IDependencyConsumer` driver's refs — the mux replays a retained
+ value only for refs a replay-opting subscriber already named). A **full rebuild** recreates every node without a
+ value, and only the publish actor knows whether the apply was one, so skipped drivers are held per correlation and
+ re-pushed when `RebuildCompleted.AddressSpaceRebuilt` (additive, default `true`) or `Degraded` says so, when the
+ outcome times out, or when the apply throws. Boot/restore applies still push every child. Pinned by
+ `DriverHostActorUnchangedResubscribeTests` (absence + mirror / VirtualTag / rebuild / degraded positive controls).
+ ⚠️ A NEW kind of value consumer (something that registers driver refs with the mux and needs a first value) must
+ join `ConsumerRefs`, or its first deploy leaves it waiting for the next value change.
- ⚠️ **A data re-subscribe must not touch the alarm feed (#662).** Every deploy's bulk push re-sends
`SetDesiredSubscriptions` to every kept driver, and `HandleSubscribeAsync` drops the prior DATA
subscription first. That teardown used to be the full `DetachSubscription`, which also unhooked
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs
index 0ae0ce274..ed9566ee1 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs
@@ -1,3 +1,4 @@
+using System.Runtime.ExceptionServices;
using System.Text.Json;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
@@ -68,8 +69,45 @@ internal sealed partial class ParsedDeploymentArtifact
};
private static readonly StringComparer DataIds = StringComparer.OrdinalIgnoreCase;
+ ///
+ /// Gitea #995 (review 2026-12-02 R-14): the data projection deserialises the whole topology (every Tag, the UNS
+ /// tables, VirtualTags, ScriptedAlarms, Scripts) and runs .
+ /// alone asked for it three times and the driver
+ /// host's catalog staging up to four more, per apply. It is now built (and validated) ONCE per node id per parsed
+ /// artifact — a throw included, re-thrown to every caller — and the three row parsers skip it entirely when the
+ /// artifact's data arrays are all empty (they could only return empty lists).
+ ///
+ private readonly Dictionary _dataProjectionByNodeId = new(StringComparer.Ordinal);
+
+ /// Diagnostics / tests (#995 R-14): how many data projections this parsed artifact actually built.
+ internal int DataProjectionBuilds { get; private set; }
+
+ private sealed class DataProjectionMemo
+ {
+ public (DraftSnapshot Snapshot, string ClusterId)? Projection;
+ public ExceptionDispatchInfo? Failure;
+ public IReadOnlyList? Errors;
+ }
+
+ /// True when none of the three data arrays carries a row (absent, or present and empty) — no data row
+ /// can then be returned, so the row parsers need no projection.
+ private bool HasNoDataRows()
+ {
+ var root = Root;
+ if (root.ValueKind != JsonValueKind.Object) return true;
+ foreach (var name in DataArrayNames)
+ if (root.TryGetProperty(name, out var value)
+ && (value.ValueKind != JsonValueKind.Array || value.GetArrayLength() != 0))
+ return false;
+ return true;
+ }
+
+ private static readonly string[] DataArrayNames = ["DataConnections", "DataExports", "RemoteNamespaceMappings"];
+
public IReadOnlyList ParseDataConnections(string nodeId)
{
+ ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
+ if (HasNoDataRows()) return [];
var projection = ReadDataProjection(nodeId);
if (projection is null)
return [];
@@ -84,6 +122,8 @@ internal sealed partial class ParsedDeploymentArtifact
public IReadOnlyList ParseDataExports(string nodeId)
{
+ ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
+ if (HasNoDataRows()) return [];
var projection = ReadDataProjection(nodeId);
if (projection is null)
return [];
@@ -96,6 +136,8 @@ internal sealed partial class ParsedDeploymentArtifact
public IReadOnlyList ParseRemoteNamespaceMappings(string nodeId)
{
+ ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
+ if (HasNoDataRows()) return [];
var projection = ReadDataProjection(nodeId);
if (projection is null)
return [];
@@ -120,6 +162,28 @@ internal sealed partial class ParsedDeploymentArtifact
private (DraftSnapshot Snapshot, string ClusterId)? ReadDataProjection(string nodeId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
+ if (!_dataProjectionByNodeId.TryGetValue(nodeId, out var memo))
+ {
+ memo = new DataProjectionMemo();
+ try { memo.Projection = BuildDataProjection(nodeId); }
+ catch (Exception ex) { memo.Failure = ExceptionDispatchInfo.Capture(ex); }
+ _dataProjectionByNodeId[nodeId] = memo;
+ }
+ memo.Failure?.Throw();
+ return memo.Projection;
+ }
+
+ /// The deployed-data validation of , computed once per memoised projection.
+ private IReadOnlyList ValidationErrors(DraftSnapshot snapshot)
+ {
+ foreach (var memo in _dataProjectionByNodeId.Values)
+ if (memo.Projection is { } p && ReferenceEquals(p.Snapshot, snapshot))
+ return memo.Errors ??= DataConnectionValidator.ValidateDeployed(snapshot).ToArray();
+ return DataConnectionValidator.ValidateDeployed(snapshot).ToArray();
+ }
+
+ private (DraftSnapshot Snapshot, string ClusterId)? BuildDataProjection(string nodeId)
+ {
var root = Root;
if (root.ValueKind != JsonValueKind.Object)
return null;
@@ -181,6 +245,7 @@ internal sealed partial class ParsedDeploymentArtifact
foreach (var m in mappings)
if (m.ConsumerNodeIds is null)
throw InvalidRow(m.RemoteNamespaceMappingId);
+ DataProjectionBuilds++;
var snapshot = new DraftSnapshot
{
GenerationId = 0,
@@ -328,11 +393,10 @@ internal sealed partial class ParsedDeploymentArtifact
}
}
- private static void ValidateRows(DraftSnapshot snapshot, IEnumerable ids)
+ private void ValidateRows(DraftSnapshot snapshot, IEnumerable ids)
{
var requested = ids.ToHashSet(DataIds);
- var error = DataConnectionValidator
- .ValidateDeployed(snapshot)
+ var error = ValidationErrors(snapshot)
.FirstOrDefault(x => x.Context is not null && requested.Contains(x.Context));
if (error is not null)
throw InvalidRow(error.Context);
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs
index 195f2fd45..1f097376e 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs
@@ -276,9 +276,42 @@ public static partial class DeploymentArtifact
try
{
using var parsed = Open(blob.ToArray());
- var root = parsed.Root;
+ return parsed.ReadClusterRedundancyMode(nodeId);
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ /// Gitea #995 (R-14): the read off an
+ /// ALREADY-parsed artifact, so the publish actor's off-thread plan step answers it from its own single parse instead
+ /// of a second inflate + parse on the pinned OPC UA thread.
+ /// The parsed artifact.
+ /// This node's host:port id.
+ /// The mode name, or null.
+ internal static string? ReadClusterRedundancyMode(ParsedDeploymentArtifact parsed, string nodeId)
+ {
+ try
+ {
+ return parsed.ReadClusterRedundancyMode(nodeId);
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+}
+
+internal sealed partial class ParsedDeploymentArtifact
+{
+ /// See .
+ internal string? ReadClusterRedundancyMode(string nodeId)
+ {
+ {
+ var root = Root;
if (!root.TryGetProperty("Clusters", out var clusters) || clusters.ValueKind != JsonValueKind.Array) return null;
- var scope = parsed.ResolveClusterScope(nodeId);
+ var scope = ResolveClusterScope(nodeId);
JsonElement? match = null;
foreach (var cluster in clusters.EnumerateArray())
{
@@ -301,11 +334,11 @@ public static partial class DeploymentArtifact
_ => null,
};
}
- catch (JsonException)
- {
- return null;
- }
}
+}
+
+public static partial class DeploymentArtifact
+{
///
/// Resolve how a node should scope a deployment artifact to its own ClusterId. Single-cluster
@@ -833,6 +866,11 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
private static string InjectScriptSource(string tagConfig, IReadOnlyDictionary scriptSourceById)
{
if (scriptSourceById.Count == 0 || string.IsNullOrWhiteSpace(tagConfig)) return tagConfig;
+ // #995 (R-14): a tag that cannot carry a scriptId is not parsed at all — once an artifact has any Scripts row this
+ // ran a JsonNode.Parse per tag of every driver. The property lookup below is ordinal and case-sensitive, so a
+ // config without the literal "scriptId" can never inject (only a \u-escaped property NAME would differ, which
+ // no authoring path emits).
+ if (!tagConfig.Contains("scriptId", StringComparison.Ordinal)) return tagConfig;
JsonNode? node;
try { node = JsonNode.Parse(tagConfig); }
catch (JsonException) { return tagConfig; }
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs
index 26f8519eb..91aba0880 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs
@@ -488,6 +488,33 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// the child the last-known-good set, not an empty one.
private readonly Dictionary _desiredByDriver = new(StringComparer.Ordinal);
+ // ---- Gitea #995 (review 2026-12-02 R-11): skip the deploy re-subscribe of an untouched driver ----
+ // A re-subscribe tears down and rebuilds the driver's whole data subscription (OpcUaClient monitored items, Galaxy
+ // advise through mxaccessgw, a forced full re-read on every poll driver) and leaves a data gap. Its only job on a
+ // KEPT driver whose desired set is unchanged is SEEDING: the initial values it produces are what give a node or a
+ // consumer that is new since the last apply its first value. So the deploy path skips a driver only when nothing
+ // that could need a seed changed for it (see SeedingFingerprint / ConsumerRefs), and re-pushes the skipped ones
+ // after the address-space outcome if the apply turned out to be a full rebuild (or degraded / timed out).
+
+ /// The child actor last handed a plain (non-acquisition) desired set for each driver. A child that is not
+ /// the current one (respawned) or that got an acquisition-demand set is never skipped.
+ private readonly Dictionary _plainPushedTo = new(StringComparer.Ordinal);
+
+ /// Per-driver seeding fingerprint from the last apply (see ).
+ private Dictionary _seedingFingerprints = new(StringComparer.Ordinal);
+
+ /// Every driver ref some mux consumer (enabled VirtualTag, enabled scripted alarm, dependency-consuming
+ /// driver such as Calculation) read at the last apply. The mux replays a retained value only for refs a
+ /// replay-opting subscriber already named, so a ref ENTERING this set needs its driver's initial value.
+ private HashSet? _consumerRefs;
+
+ /// The drivers hosted here, keyed like .
+ private readonly Dictionary _depConsumers = new(StringComparer.Ordinal);
+
+ /// Drivers whose deploy re-subscribe was skipped, held per apply correlation until the address-space
+ /// outcome says whether their nodes survived (non-rebuild, clean) or were recreated (re-push them).
+ private readonly Dictionary> _seedAfterAddressSpace = new();
+
///
/// Cached local from the latest
/// snapshot (null = unknown until the first snapshot arrives, or no local node match). The Primary
@@ -3372,7 +3399,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// resumes off the actor thread.
// SubscribeBulk pass: hand each driver its desired tag references so live values flow into
// the just-rebuilt address space instead of staying BadWaitingForInitialData.
- PushDesiredSubscriptionsFromParsed(msg.DeploymentId, parsed);
+ // #995 R-11: a kept driver with nothing seedable changed is NOT re-subscribed; if the address-space apply
+ // turns out to be a rebuild (its nodes recreated empty), HandleRebuildCompleted re-pushes it.
+ var skippedResubscribes = PushDesiredSubscriptionsFromParsed(msg.DeploymentId, parsed, skipUnchanged: true);
+ // Recorded at once, so a throw in the steps below still re-pushes them (the catch). No publish actor ⇒ no
+ // address space whose rebuild could recreate a skipped driver's nodes.
+ if (_opcUaPublishActor is not null && skippedResubscribes.Count > 0)
+ _seedAfterAddressSpace[msg.Correlation] = new HashSet(skippedResubscribes, StringComparer.Ordinal);
// Cache the applied bytes as this node's last-known-good (idempotent store; skips empty).
CacheAppliedArtifact(msg.DeploymentId, msg.Revision, appliedBlob, parsed);
var catalogFailed = _opcUaPublishActor is null && _catalogAttempt is not null
@@ -3403,6 +3436,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// A throw after the Applied ack was put on hold — the Failed ack below is this apply's one
// answer, so the held Applied must never follow it when the address-space outcome lands.
DropPendingAck(msg.Correlation);
+ // #995 R-11: the routing/desired state may be half-applied — re-push anything this apply skipped.
+ SeedSkippedDrivers(msg.Correlation, reseed: true, "the apply threw");
// #977 R-15: whatever revision is current now, a throw part-way through the apply means the drivers and the
// routing maps (ApplyDesiredSubscriptions clears them before repopulating) may already be the NEW revision's,
// partially. Nothing about the current revision is known-served any more, so a re-dispatch of EITHER revision
@@ -3474,6 +3509,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
///
private void HandleRebuildCompleted(OpcUa.OpcUaPublishActor.RebuildCompleted msg)
{
+ SeedSkippedDrivers(msg.Correlation, reseed: msg.AddressSpaceRebuilt || msg.Degraded,
+ msg.Degraded ? "degraded apply" : "full rebuild");
if (!_pendingAcks.Remove(msg.Correlation, out var pending))
{
_log.Debug("DriverHost {Node}: address-space outcome for {Correlation} has no held ack (already timed out or superseded); dropping",
@@ -3492,6 +3529,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
///
private void HandleApplyOutcomeTimedOut(ApplyOutcomeTimedOut msg)
{
+ SeedSkippedDrivers(msg.Correlation, reseed: true, "address-space outcome not reported in time");
if (!_pendingAcks.Remove(msg.Correlation, out var pending)) return;
ReleasePendingAck(pending, degraded: true,
@@ -4091,7 +4129,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
///
/// The deployment being applied — diagnostics only.
/// The apply's parsed artifact.
- private void PushDesiredSubscriptionsFromParsed(DeploymentId deploymentId, ParsedDeploymentArtifact parsed)
+ /// #995 R-11: the deploy path skips the re-subscribe of a driver with nothing
+ /// seedable changed (see ).
+ /// The drivers whose re-subscribe was skipped (empty unless ).
+ private IReadOnlyCollection PushDesiredSubscriptionsFromParsed(
+ DeploymentId deploymentId, ParsedDeploymentArtifact parsed, bool skipUnchanged = false)
{
AddressSpaceComposition composition;
try
@@ -4101,10 +4143,10 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
catch (Exception ex)
{
_log.Warning(ex, "DriverHost {Node}: failed to parse composition for SubscribeBulk ({Id})", _localNode, deploymentId);
- return;
+ return Array.Empty();
}
- ApplyDesiredSubscriptions(composition);
+ return ApplyDesiredSubscriptions(composition, skipUnchanged);
}
/// Gets (creating on first use) the per-driver bucket of a secondary index.
@@ -4125,7 +4167,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// Equipment VirtualTag + ScriptedAlarm plans to their hosts.
///
/// The composition this node should serve.
- private void ApplyDesiredSubscriptions(AddressSpaceComposition composition)
+ ///
+ /// #995 R-11 (deploy path only): do not re-push a kept driver whose seeding fingerprint is unchanged and none of
+ /// whose value refs gained a mux consumer. The caller re-pushes the returned drivers if the address-space apply
+ /// turns out to be a rebuild. Every other path (boot, restore) pushes every child, as before.
+ ///
+ /// The drivers whose push was skipped.
+ private IReadOnlyCollection ApplyDesiredSubscriptions(AddressSpaceComposition composition, bool skipUnchanged = false)
{
_catalogCoordinator?.BeforeSubscriptionApplyForTests?.Invoke();
// v3 Batch 4: the driver subscribes + publishes by RawPath (the wire-ref == RawPath == RawTagPlan.NodeId
@@ -4300,9 +4348,29 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
alarmRefsByDriver.TryGetValue(driverId, out var ar) ? ar : Array.Empty());
}
+ // #995 R-11: what a re-subscribe would seed, per driver, and which refs gained a mux consumer since the last apply.
+ var previousFingerprints = _seedingFingerprints;
+ _seedingFingerprints = new Dictionary(StringComparer.Ordinal);
+ foreach (var driverId in _desiredByDriver.Keys)
+ _seedingFingerprints[driverId] = SeedingFingerprint(driverId, composition);
+ var previousConsumerRefs = _consumerRefs;
+ _consumerRefs = ConsumerRefs(composition);
+ HashSet? newConsumerRefs = null;
+ if (previousConsumerRefs is not null)
+ {
+ newConsumerRefs = new HashSet(_consumerRefs, StringComparer.Ordinal);
+ newConsumerRefs.ExceptWith(previousConsumerRefs);
+ }
+
var total = 0;
+ List? skipped = null;
foreach (var (driverId, entry) in _children)
{
+ if (skipUnchanged && CanSkipResubscribe(driverId, entry.Actor, previousFingerprints, newConsumerRefs))
+ {
+ (skipped ??= new List()).Add(driverId);
+ continue;
+ }
total += SendDesiredSubscriptions(entry.Actor, driverId);
}
@@ -4311,6 +4379,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_log.Info("DriverHost {Node}: SubscribeBulk pushed {Refs} references across {Drivers} driver(s)",
_localNode, total, refsByDriver.Count);
}
+ if (skipped is not null)
+ {
+ _log.Info("DriverHost {Node}: SubscribeBulk kept {Count} unchanged driver subscription(s) without re-subscribing ({Drivers})",
+ _localNode, skipped.Count, string.Join(", ", skipped));
+ }
// Hand the Equipment-namespace VirtualTags to the host so it spawns/reconciles a
// VirtualTagActor per plan and streams their evaluated values back onto the just-rebuilt
@@ -4339,6 +4412,84 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_log.Info("DriverHost {Node}: applied {Count} Equipment ScriptedAlarm(s) to the ScriptedAlarm host",
_localNode, composition.EquipmentScriptedAlarms.Count);
}
+
+ return (IReadOnlyCollection?)skipped ?? Array.Empty();
+ }
+
+ ///
+ /// #995 R-11: whether the deploy push to can be skipped. Only when the child is the
+ /// one that already holds a plain (non-acquisition) set from this host, that set and everything it seeds are
+ /// unchanged (), and none of its value refs gained a mux consumer — any of those
+ /// means some node or consumer may be new and needs the initial values a re-subscribe produces.
+ ///
+ private bool CanSkipResubscribe(string driverId, IActorRef child, Dictionary previousFingerprints,
+ HashSet? newConsumerRefs)
+ {
+ if (newConsumerRefs is null) return false; // first apply of this incarnation
+ if (_acquisitionDemands.ContainsKey(driverId)) return false;
+ if (!_plainPushedTo.TryGetValue(driverId, out var pushed) || !pushed.Equals(child)) return false;
+ if (!previousFingerprints.TryGetValue(driverId, out var before)
+ || !_seedingFingerprints.TryGetValue(driverId, out var now)
+ || !before.AsSpan().SequenceEqual(now)) return false;
+ if (newConsumerRefs.Count > 0 && _desiredByDriver.TryGetValue(driverId, out var set))
+ foreach (var r in set.ValueRefs)
+ if (newConsumerRefs.Contains(r)) return false;
+ return true;
+ }
+
+ ///
+ /// #995 R-11: everything a deploy re-subscribe of would (re)seed — its value refs, each
+ /// with its fan-out NodeIds (raw + every referencing UNS mirror, so a new or re-pointed mirror changes it) and its
+ /// historization (a ref that starts being recorded), then its alarm refs. Built after the routing maps.
+ ///
+ private string[] SeedingFingerprint(string driverId, AddressSpaceComposition composition)
+ {
+ var set = _desiredByDriver[driverId];
+ var historized = new Dictionary(StringComparer.Ordinal);
+ foreach (var t in composition.RawTags)
+ if (string.Equals(t.DriverInstanceId, driverId, StringComparison.Ordinal))
+ historized[t.NodeId] = t.IsHistorized ? "H:" + t.HistorianTagname : "-";
+ var parts = new List(set.ValueRefs.Count + set.AlarmRefs.Count + 1);
+ foreach (var r in set.ValueRefs)
+ {
+ var nodes = _nodeIdByDriverRef.TryGetValue((driverId, r), out var fan)
+ ? string.Join("|", fan.Select(n => n.Realm + ":" + n.NodeId).Order(StringComparer.Ordinal))
+ : string.Empty;
+ parts.Add("v\u0001" + r + "\u0001" + historized.GetValueOrDefault(r, "-") + "\u0001" + nodes);
+ }
+ parts.Add("alarms");
+ foreach (var r in set.AlarmRefs) parts.Add("a\u0001" + r);
+ return parts.ToArray();
+ }
+
+ /// #995 R-11: every ref a mux consumer reads under — enabled VirtualTags,
+ /// enabled scripted alarms and the hosted dependency-consuming drivers (read after the apply's reconcile).
+ private HashSet ConsumerRefs(AddressSpaceComposition composition)
+ {
+ var refs = new HashSet(StringComparer.Ordinal);
+ foreach (var vt in composition.EquipmentVirtualTags)
+ if (vt.Enabled) refs.UnionWith(vt.DependencyRefs);
+ foreach (var a in composition.EquipmentScriptedAlarms)
+ if (a.Enabled) refs.UnionWith(a.DependencyRefs);
+ foreach (var consumer in _depConsumers.Values) refs.UnionWith(consumer.DependencyRefs);
+ return refs;
+ }
+
+ /// #995 R-11: re-push the drivers an apply skipped, once its address-space outcome says their nodes were
+ /// recreated (a rebuild), may be partial (degraded) or is unknown (timed out). Always forgets the entry.
+ private void SeedSkippedDrivers(CorrelationId correlation, bool reseed, string why)
+ {
+ if (!_seedAfterAddressSpace.Remove(correlation, out var skipped) || !reseed) return;
+ var pushed = 0;
+ foreach (var driverId in skipped)
+ if (_children.TryGetValue(driverId, out var child))
+ {
+ SendDesiredSubscriptions(child.Actor, driverId);
+ pushed++;
+ }
+ if (pushed > 0)
+ _log.Info("DriverHost {Node}: re-subscribing {Count} kept driver(s) after the address-space apply ({Why})",
+ _localNode, pushed, why);
}
///
@@ -4363,8 +4514,17 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
{
var demand = _acquisitionDemands.GetValueOrDefault(driverId);
var message = BuildDesiredSubscriptions(driverId, demand);
- if (demand is null) actor.Tell(message);
- else if (!_acquisitionPending.ContainsKey(driverId)) StartAcquisitionDemand(driverId, demand, ActorRefs.Nobody);
+ if (demand is null)
+ {
+ actor.Tell(message);
+ _plainPushedTo[driverId] = actor;
+ }
+ else
+ {
+ // #995 R-11: an acquisition-demand set is not the plain set a later deploy could compare against.
+ _plainPushedTo.Remove(driverId);
+ if (!_acquisitionPending.ContainsKey(driverId)) StartAcquisitionDemand(driverId, demand, ActorRefs.Nobody);
+ }
return message.FullReferences.Count;
}
@@ -4792,6 +4952,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyConsumerMuxAdapter.Props(consumer, _dependencyMux),
"depmux-" + actorName);
_depConsumerAdapters[spec.DriverInstanceId] = adapter;
+ _depConsumers[spec.DriverInstanceId] = consumer;
_log.Info("DriverHost {Node}: wired dependency-consumer mux adapter for {Id} ({Count} ref(s))",
_localNode, spec.DriverInstanceId, consumer.DependencyRefs.Count);
}
@@ -4804,6 +4965,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// driver child is stopped/respawned so a stale adapter never keeps a dead driver's refs registered.
private void StopDependencyAdapter(string driverInstanceId)
{
+ _depConsumers.Remove(driverInstanceId);
if (_depConsumerAdapters.Remove(driverInstanceId, out var adapter))
Context.Stop(adapter);
}
@@ -4825,6 +4987,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(driverInstanceId);
Context.Stop(entry.Actor);
_children.Remove(driverInstanceId);
+ _plainPushedTo.Remove(driverInstanceId);
// A1 review S2: the stopped incarnation can no longer vouch for its conditions (a respawn's carried-over
// known state would otherwise stand until the new incarnation signals). No-op when the deploy removed them.
WithdrawDriverConditionsKnown(driverInstanceId);
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs
index 6365f4a32..a28ea08a1 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs
@@ -139,10 +139,15 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// ack only after that reply, so a degraded apply can no longer seal a deployment green. Off for the
/// boot/restore paths, which re-ack nothing.
///
+ ///
+ /// Gitea #995 (R-14): SHA-256 (lower hex) of , computed ONCE by the actor when the request
+ /// arrives and reused for the catalog attempt, the data-catalog generation and the data-plane authority revision
+ /// — it used to be hashed up to three times on the pinned OPC UA thread. Callers leave it null.
+ ///
public sealed record RebuildAddressSpace(
CorrelationId Correlation, DeploymentId? DeploymentId = null, byte[]? Artifact = null,
bool ReportOutcome = false, DataConnections.CatalogAttempt? CatalogAttempt = null,
- bool StageCatalog = false);
+ bool StageCatalog = false, string? ArtifactRevision = null);
///
/// the reply to a carrying
@@ -156,8 +161,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// stale. An empty plan (nothing changed) is clean.
///
/// A short operator-readable reason; null when clean.
+ ///
+ /// Gitea #995 (R-11): only when the apply was a clean NON-rebuild — every node that
+ /// existed before it still exists with its value. DriverHostActor skips the re-subscribe of a driver
+ /// whose desired set and fan-out are unchanged, and re-pushes those drivers when this is
+ /// (a full rebuild recreated their nodes without a value). Defaults to — the
+ /// conservative answer for any producer that does not know.
+ ///
public sealed record RebuildCompleted(
- CorrelationId Correlation, DeploymentId? DeploymentId, bool Degraded, string? DegradedReason);
+ CorrelationId Correlation, DeploymentId? DeploymentId, bool Degraded, string? DegradedReason,
+ bool AddressSpaceRebuilt = true);
public sealed record ServiceLevelChanged(byte ServiceLevel);
@@ -175,11 +188,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private sealed record PlanReady(
object Incarnation, RebuildAddressSpace Request, IActorRef Requester, byte[] Artifact,
DataPlaneAuthorityProjection? Authority, Exception? AuthorityError,
- AddressSpaceComposition Composition, AddressSpacePlan Plan, IReadOnlyList Inconsistencies);
+ AddressSpaceComposition Composition, AddressSpacePlan Plan, IReadOnlyList Inconsistencies,
+ string? ClusterRedundancyMode = null);
/// The off-thread parse / plan step threw (unreadable bytes, a composer fault).
private sealed record PlanFailed(object Incarnation, RebuildAddressSpace Request, IActorRef Requester,
- Exception Error, DataPlaneAuthorityProjection? Authority = null, byte[]? Artifact = null);
+ Exception Error, DataPlaneAuthorityProjection? Authority = null, byte[]? Artifact = null,
+ string? ClusterRedundancyMode = null);
/// Test seams for the off-thread plan step. Production passes none.
internal sealed class TestHooks
@@ -189,6 +204,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
internal Action? BeforePlan { get; init; }
internal Action? BeforeComposition { get; init; }
+ /// #995 R-14: observes every artifact redundancy-mode read (the reading thread's managed id), so a test can
+ /// assert it ran on the plan step rather than the actor thread.
+ internal Action? OnRedundancyModeRead { get; init; }
+
/// Replaces (a test makes it throw).
internal Func? ParseAuthority { get; init; }
}
@@ -483,12 +502,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
IDataPlaneAuthoritySink? dataPlaneAuthority = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataConnections.DataConnectionWarmRoleView? dataWarmRole = null,
- DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) =>
+ DataConnections.DataConnectionDeploymentRuntime? dataConnections = null,
+ WarmRedundancySettings? redundancy = null) =>
// CreateBy, not Create(expression): Akka's expression path activates through a PUBLIC constructor, and the
// seam-carrying constructor is internal so the test seams stay off the public API (review M3).
Akka.Actor.Props.CreateBy(new TestProducer(() => new OpcUaPublishActor(
sink, NullServiceLevelPublisher.Instance, false, localNode, null, applier, null, null, null, null,
- false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null,
+ false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null, redundancy: redundancy,
catalogCoordinator: catalogCoordinator, dataWarmRole: dataWarmRole, dataConnections: dataConnections)));
/// Produces the actor through its internal (seam-carrying) constructor, for .
@@ -876,16 +896,23 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private void HandleRebuild(RebuildAddressSpace msg)
{
+ // #995 R-14: hash the artifact ONCE; the catalog attempt, the data-catalog generation and the authority revision
+ // all reuse it. The redundancy-mode cross-check is no longer a second full parse here: the plan step reads it
+ // from its own parse, off this pinned thread (CheckRedundancyMode on PlanReady/PlanFailed).
+ msg = WithArtifactRevision(msg);
if (_catalogCoordinator is not null && msg.CatalogAttempt is null)
- {
- var revision = msg.Artifact is { Length: > 0 } bytes
- ? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)) : "unavailable";
- msg = msg with { CatalogAttempt = _catalogCoordinator.BeginAttempt(revision), StageCatalog = true };
- }
- if (msg.Artifact is { Length: > 0 } artifact) CheckRedundancyMode(artifact);
+ msg = msg with { CatalogAttempt = _catalogCoordinator.BeginAttempt(msg.ArtifactRevision!), StageCatalog = true };
StartRebuild(msg, Sender);
}
+ /// #995 R-14: stamp the request with its artifact's SHA-256 (or "unavailable"), unless it already carries it.
+ private static RebuildAddressSpace WithArtifactRevision(RebuildAddressSpace msg) =>
+ msg.ArtifactRevision is not null ? msg : msg with
+ {
+ ArtifactRevision = msg.Artifact is { Length: > 0 } bytes
+ ? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)) : "unavailable",
+ };
+
private void StageStandaloneCatalog(RebuildAddressSpace msg, ParsedDeploymentArtifact parsed)
{
if (_catalogCoordinator is null || msg.CatalogAttempt is null) return;
@@ -937,9 +964,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
// Close the data-service generation before any fallible parse or topology work. Ordinary
// local OPC UA availability remains independent; remote/mapped access uses this barrier.
- var desiredRevision = msg.Artifact is { Length: > 0 } desiredBytes
- ? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(desiredBytes))
- : "unavailable";
+ msg = WithArtifactRevision(msg);
+ var desiredRevision = msg.ArtifactRevision!;
if (_catalogCoordinator is null) _dataCatalogEpoch = _dataCatalog.Begin(desiredRevision);
// Only a node with NO applier at all (the F10b/dev seam) falls back to the raw-sink rebuild — and that
@@ -947,6 +973,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
// real driver node that has an applier (that node diff-and-applies from its in-hand bytes below).
if (_applier is null)
{
+ if (msg.Artifact is { Length: > 0 } modeBytes && WantsRedundancyModeCheck())
+ CheckRedundancyMode(ReadRedundancyModeSafe(modeBytes, _localNode!.Value.Value, _hooks));
if (msg.StageCatalog && msg.Artifact is { Length: > 0 } standaloneBytes)
{
try { using var parsed = DeploymentArtifact.Open(standaloneBytes); StageStandaloneCatalog(msg, parsed); }
@@ -1000,6 +1028,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
var baseComposition = _lastApplied;
var nodeId = _localNode?.Value;
var wantAuthority = _dataPlaneAuthority is not null && _catalogCoordinator is null;
+ var wantMode = WantsRedundancyModeCheck();
var incarnation = _incarnation;
var hooks = _hooks;
Task.Run