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(() => @@ -1009,6 +1038,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers // result — and an empty composition is not a benign no-op here (see the no-bytes guard above). The // throw lands in PlanFailed: logged at Error, _lastApplied untouched, last-known-good still served. using var parsed = DeploymentArtifact.Open(artifact); + // #995 R-14: the redundancy-mode cross-check reads this parse (it used to be a second full inflate + + // parse of the artifact on the pinned actor thread). Compared and logged back on the actor thread. + string? clusterMode = null; + if (wantMode && nodeId is not null) + { + hooks?.OnRedundancyModeRead?.Invoke(Environment.CurrentManagedThreadId); + // A diagnostic read: whatever it throws must never fail the address-space plan. + try { clusterMode = DeploymentArtifact.ReadClusterRedundancyMode(parsed, nodeId); } + catch (Exception) { clusterMode = null; } + } if (msg.StageCatalog) StageStandaloneCatalog(msg, parsed); // The authority parse is isolated from the address-space plan (review fix I2): before the plan moved // off-thread a throw here was contained by FeedDataPlaneAuthority's own catch; it must not now @@ -1037,13 +1076,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers ? parsed.ParseComposition(nodeId, inconsistencies.Add) : parsed.ParseComposition(); var plan = AddressSpacePlanner.Compute(baseComposition, composition); - return new PlanReady(incarnation, msg, requester, artifact, authority, authorityError, composition, plan, inconsistencies); + return new PlanReady(incarnation, msg, requester, artifact, authority, authorityError, composition, plan, inconsistencies, + clusterMode); } catch (Exception ex) { // Parsed revocations remain independent of topology planning. Transfer them back // to the actor thread even when no address-space plan could be constructed. - return new PlanFailed(incarnation, msg, requester, ex, authority, artifact); + return new PlanFailed(incarnation, msg, requester, ex, authority, artifact, clusterMode); } }) .PipeTo(Self, failure: ex => new PlanFailed(incarnation, msg, requester, ex)); @@ -1052,6 +1092,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers private void HandlePlanReady(PlanReady ready) { if (IsFromAnotherIncarnation(ready.Incarnation, ready.Request, ready.Requester)) return; + CheckRedundancyMode(ready.ClusterRedundancyMode); if (ready.AuthorityError is { } authorityError) _log.Error(authorityError, @@ -1075,9 +1116,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers private void HandlePlanFailed(PlanFailed failed) { if (IsFromAnotherIncarnation(failed.Incarnation, failed.Request, failed.Requester)) return; + CheckRedundancyMode(failed.ClusterRedundancyMode); if (failed.Authority is not null && failed.Artifact is not null) - FeedDataPlaneAuthority(failed.Authority, failed.Artifact); + FeedDataPlaneAuthority(failed.Authority, failed.Artifact, failed.Request.ArtifactRevision); _planInFlight = false; _log.Error(failed.Error, "OpcUaPublish: rebuild pipeline threw (correlation={Correlation})", failed.Request.Correlation); @@ -1484,6 +1526,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers outcome = (true, $"address-space completion threw: {ex.Message}"); } + // #995 R-11: captured before the replay scope is reset — a rebuild (or the applier-less raw-sink rebuild) recreated + // every node, so the driver host must re-seed values it skipped re-subscribing. + var rebuilt = _applier is null || _replayScope.AllVariables; + // Land what arrived while the plan was in flight on the nodes the apply just created — before the answer, // so "applied" means the deferred first values are on the address space too (review fix C1). ReplayDeferredWrites(_replayScope); @@ -1497,7 +1543,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers } if (msg.ReportOutcome) - requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason)); + requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason, + AddressSpaceRebuilt: rebuilt)); } /// The actor-thread half of a rebuild: install the artifact's authority, apply the plan through the @@ -1570,7 +1617,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers // feeding this after that return would leave a revoked key authenticating until some unrelated // structural change happened to redeploy. Authorization and topology change on their own // schedules. - if (ready.Authority is not null) FeedDataPlaneAuthority(ready.Authority, ready.Artifact); + if (ready.Authority is not null) FeedDataPlaneAuthority(ready.Authority, ready.Artifact, ready.Request.ArtifactRevision); var composition = ready.Composition; var plan = ready.Plan; @@ -1860,7 +1907,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// The keys + grants decoded (off-thread) from the rebuild's single parse of the artifact. /// The RAW artifact bytes — hashed for the revision id, which must be /// SHA-256 of the exact blob (see below); never re-parsed here. - private void FeedDataPlaneAuthority(DataPlaneAuthorityProjection projection, byte[] artifactBytes) + /// #995 R-14: the request's already-computed SHA-256 of ; hashed + /// here only when absent. + private void FeedDataPlaneAuthority(DataPlaneAuthorityProjection projection, byte[] artifactBytes, string? revision = null) { if (_dataPlaneAuthority is null) return; @@ -1870,7 +1919,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers // which is what lets a node recognise a re-applied revision without the hash riding the wire. // Hashed off the RAW bytes for exactly that reason: a re-serialisation of the parsed document // would be a different byte sequence and would not match the deployment's RevisionHash. - var revision = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(artifactBytes)); + revision ??= Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(artifactBytes)); var snapshot = _dataPlaneAuthority.Apply( projection.ClusterId, revision, projection.Keys, projection.Grants, projection.ScopePaths, projection.EquipmentScopePaths, projection.ScriptedAlarmOwners, projection.UnsFolderScopes, @@ -2364,21 +2413,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// counts otopcua.redundancy.mode_mismatch. The node keeps its local mode — the only value available /// before SDK start. Unset has opted out and is not checked. /// - /// The applied artifact bytes. - private void CheckRedundancyMode(byte[] artifact) + /// The artifact's cluster mode, read off the plan step's parse (#995 R-14); null when the + /// artifact does not say or could not be read. + private void CheckRedundancyMode(string? clusterMode) { - if (_redundancy.Mode == OpcUaRedundancyMode.Unset || _localNode is null) return; - string? clusterMode; - try - { - clusterMode = DeploymentArtifact.ReadClusterRedundancyMode(artifact, _localNode.Value.Value); - } - catch (Exception ex) - { - _log.Debug(ex, "OpcUaPublish: could not read the artifact's cluster RedundancyMode"); - return; - } - + if (!WantsRedundancyModeCheck()) return; if (clusterMode is null) return; if (string.Equals(clusterMode, _redundancy.Mode.ToString(), StringComparison.OrdinalIgnoreCase)) return; OtOpcUaTelemetry.RedundancyModeMismatch.Add(1, @@ -2389,6 +2428,17 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers clusterMode, _redundancy.Mode, _redundancy.Mode); } + /// Whether the #717 deploy-time redundancy-mode cross-check applies on this node. + private bool WantsRedundancyModeCheck() => _redundancy.Mode != OpcUaRedundancyMode.Unset && _localNode is not null; + + /// The applier-less (dev) path's synchronous redundancy-mode read; never throws. + private static string? ReadRedundancyModeSafe(byte[] artifact, string nodeId, TestHooks? hooks) + { + hooks?.OnRedundancyModeRead?.Invoke(Environment.CurrentManagedThreadId); + try { return DeploymentArtifact.ReadClusterRedundancyMode(artifact, nodeId); } + catch (Exception) { return null; } + } + private void ScheduleWarmRetry() => Timers.StartSingleTimer("warm-retry", WarmRetry.Instance, TimeSpan.FromSeconds(1)); /// The legacy role-only ServiceLevel switch (primary-leader → 240, primary → 200, diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DeploymentArtifactApplyCostTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DeploymentArtifactApplyCostTests.cs new file mode 100644 index 000000000..8b46546ed --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DeploymentArtifactApplyCostTests.cs @@ -0,0 +1,109 @@ +using System.Text; +using System.Text.Json.Nodes; +using Akka.Actor; +using Microsoft.Extensions.Logging.Abstractions; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// Gitea #995 (review 2026-12-02 R-14): apply-time artifact work was repeated. The data projection (a full +/// deserialise of every topology table + ValidateDeployed) ran three times inside +/// ParseDataPlaneAuthority alone — even for a node with ZERO data rows, because the composer always emits the +/// three arrays — and up to four more in the driver host's catalog staging. The publish actor also re-parsed the +/// whole artifact on its pinned thread just to read the cluster's redundancy mode, and hashed it up to three times. +/// +public sealed class DeploymentArtifactApplyCostTests : RuntimeActorTestBase +{ + [Fact] + public void One_data_projection_serves_every_consumer_of_one_parsed_artifact() + { + using var parsed = DeploymentArtifact.Open(GrpcDataCatalogStagingTests.Artifact()); + + // Exactly the calls one apply makes (DriverHostActor.StageCatalog): authority (3 row parses inside) + snapshot + + // connections + mappings + connections again. + var authority = parsed.ParseDataPlaneAuthority("node-a"); + parsed.ParseLocalCatalogSnapshot("node-a").ShouldNotBeNull(); + parsed.ParseDataConnections("node-a"); + parsed.ParseRemoteNamespaceMappings("node-a"); + parsed.ParseDataConnections("node-a"); + parsed.ParseDataExports("node-a").Count.ShouldBe(1, "the projection still answers (positive control)"); + + authority.CatalogValid.ShouldBeTrue(); + parsed.DataProjectionBuilds.ShouldBe(1); + } + + [Fact] + public void An_artifact_with_empty_data_arrays_builds_no_projection_for_the_authority() + { + var root = JsonNode.Parse(GrpcDataCatalogStagingTests.Artifact())!.AsObject(); + root["DataExports"] = new JsonArray(); + using var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString())); + + var authority = parsed.ParseDataPlaneAuthority("node-a"); + + authority.Keys.Count.ShouldBe(1, "keys still parse (positive control)"); + parsed.ParseDataConnections("node-a").ShouldBeEmpty(); + parsed.ParseDataExports("node-a").ShouldBeEmpty(); + parsed.ParseRemoteNamespaceMappings("node-a").ShouldBeEmpty(); + parsed.DataProjectionBuilds.ShouldBe(0); + } + + [Fact] + public void An_invalid_data_row_still_fails_every_row_parser_from_the_memoised_projection() + { + using var parsed = DeploymentArtifact.Open(GrpcDataCatalogStagingTests.Artifact(invalidExport: true)); + + Should.Throw(() => parsed.ParseDataExports("node-a")); + Should.Throw(() => parsed.ParseDataExports("node-a")); + parsed.ParseDataPlaneAuthority("node-a").CatalogValid.ShouldBeFalse(); + parsed.DataProjectionBuilds.ShouldBe(1); + } + + [Fact] + public void The_redundancy_mode_cross_check_reads_the_plan_steps_parse_not_the_actor_thread() + { + var planThread = 0; + var readThreads = new List(); + var hooks = new OpcUaPublishActor.TestHooks + { + BeforePlan = () => Volatile.Write(ref planThread, Environment.CurrentManagedThreadId), + OnRedundancyModeRead = id => { lock (readThreads) readThreads.Add(id); }, + }; + var sink = new NullSink(); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests( + sink, new AddressSpaceApplier(sink, NullLogger.Instance), hooks, + localNode: NodeId.Parse("x:1"), redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm))); + var artifact = Encoding.UTF8.GetBytes("{\"Clusters\":[{\"ClusterId\":\"c1\",\"RedundancyMode\":\"None\"}],\"Nodes\":[]}"); + + EventFilter.Error(contains: "RedundancyMode for this node's cluster is None").ExpectOne(() => + { + actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact, ReportOutcome: true)); + ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + }, TestContext.Current.CancellationToken); + + lock (readThreads) readThreads.ShouldBe([Volatile.Read(ref planThread)], "one read, on the plan step's thread"); + } + + private sealed class NullSink : IOpcUaAddressSpaceSink + { + public void WriteValue(string nodeId, object? value, uint statusCode, DateTime ts, AddressSpaceRealm realm) { } + public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime ts, AddressSpaceRealm realm) { } + public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime ts, AddressSpaceRealm realm) { } + public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { } + public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { } + public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { } + public void RebuildAddressSpace() { } + public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { } + public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { } + public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnchangedResubscribeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnchangedResubscribeTests.cs new file mode 100644 index 000000000..e6d489e74 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnchangedResubscribeTests.cs @@ -0,0 +1,180 @@ +using Akka.Actor; +using Akka.TestKit; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Commons.Engines; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// Gitea #995 (review 2026-12-02 R-11): every deploy used to re-subscribe every kept driver's whole data set — +/// upstream monitored-item delete/create, Galaxy unadvise/advise, a forced full re-read, a data gap — even when the +/// deploy did not touch that driver. A kept driver whose desired set and everything it seeds are unchanged is now +/// left alone on a NON-rebuild apply. The re-subscribe's seeding job is kept: a new UNS mirror, a new mux consumer +/// of one of the driver's refs, or an address-space REBUILD (nodes recreated empty) still re-push it. +/// +public sealed class DriverHostActorUnchangedResubscribeTests : RuntimeActorTestBase +{ + private static readonly NodeId TestNode = NodeId.Parse("node-1:4053"); + private const string SpeedPath = "Plant/Modbus/dev1/speed"; + private const string Equipment = "EQ-filling-line1-station1"; + + private static readonly (string, string, string, string, string, bool)[] OneDriver = + [("drv-1", "Modbus", "dev1", "speed", "Float", false)]; + + private static readonly (string, string, string, string, string, bool)[] TwoDrivers = + [("drv-1", "Modbus", "dev1", "speed", "Float", false), ("drv-2", "Modbus2", "dev2", "pressure", "Float", false)]; + + private static readonly (string, string, string, string, string?)[] NoRefs = []; + + /// An unrelated deploy no longer re-subscribes drv-1; a deploy adding a UNS mirror of its tag does + /// (the positive control that also orders drv-1's mailbox: had the first deploy pushed, the count would be 3). + [Fact] + public void A_kept_driver_is_not_resubscribed_by_an_unrelated_non_rebuild_deploy_but_is_by_a_new_mirror() + { + var rig = new Rig(this, NewInMemoryDbFactory()); + rig.Deploy(OneDriver, NoRefs, Rev('a')); + var drv1 = rig.Driver("drv-1"); + AwaitAssert(() => drv1.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + + // Deploy B adds an unrelated driver. Its own push (drv-2 subscribes) is the presence half. + rig.Deploy(TwoDrivers, NoRefs, Rev('b')); + AwaitAssert(() => rig.Driver("drv-2").SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + + // Deploy C adds a UNS reference to drv-1's tag: the new mirror needs a seed, so drv-1 IS re-pushed. + rig.Deploy(TwoDrivers, [("filling", "line1", "station1", "speed", null)], Rev('c')); + AwaitAssert(() => drv1.SubscribeCount.ShouldBeGreaterThanOrEqualTo(2), PresenceBudget, cancellationToken: Ct); + // Mailbox order: B's push (had it been sent) precedes C's, so exactly 2 means B was skipped. + Thread.Sleep(300); + drv1.SubscribeCount.ShouldBe(2, "the unrelated deploy B re-subscribed drv-1"); + rig.Driver("drv-2").SubscribeCount.ShouldBe(1, "deploy C did not touch drv-2"); + factoryCreatedOnce(rig); + } + + /// A full rebuild recreates every node without a value: the skipped driver is re-pushed once the + /// address-space outcome reports the rebuild. + [Fact] + public void A_skipped_driver_is_re_pushed_when_the_address_space_apply_was_a_rebuild() + { + var rig = new Rig(this, NewInMemoryDbFactory()); + rig.Deploy(OneDriver, NoRefs, Rev('a')); + var drv1 = rig.Driver("drv-1"); + AwaitAssert(() => drv1.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + + rig.Rebuilt = true; + rig.Deploy(TwoDrivers, NoRefs, Rev('b')); + AwaitAssert(() => drv1.SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct); + } + + /// A degraded apply may have left nodes missing: re-push too. + [Fact] + public void A_skipped_driver_is_re_pushed_when_the_address_space_apply_was_degraded() + { + var rig = new Rig(this, NewInMemoryDbFactory()); + rig.Deploy(OneDriver, NoRefs, Rev('a')); + var drv1 = rig.Driver("drv-1"); + AwaitAssert(() => drv1.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + + rig.Degraded = true; + rig.Deploy(TwoDrivers, NoRefs, Rev('b'), expectDegraded: true); + AwaitAssert(() => drv1.SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct); + } + + /// A new VirtualTag reading drv-1's tag registers with the mux, which replays a retained value only for refs + /// some replay-opting subscriber already named — so its first input has to come from a re-subscribe. + [Fact] + public void A_new_virtual_tag_consumer_of_a_kept_drivers_ref_re_pushes_that_driver() + { + var rig = new Rig(this, NewInMemoryDbFactory()); + var equip = new[] { ("filling", "line1", "station1", "speed", (string?)null) }; + rig.Deploy(OneDriver, equip, Rev('a')); + var drv1 = rig.Driver("drv-1"); + AwaitAssert(() => drv1.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + + rig.Deploy(OneDriver, equip, Rev('b'), + virtualTags: [("vt-1", Equipment, "Doubled", $"return (double)ctx.GetTag(\"{SpeedPath}\").Value * 2;")]); + AwaitAssert(() => drv1.SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct); + + // ...and a further unrelated deploy with the same VirtualTag does not (the consumer is no longer new). + rig.Deploy(TwoDrivers, equip, Rev('c'), + virtualTags: [("vt-1", Equipment, "Doubled", $"return (double)ctx.GetTag(\"{SpeedPath}\").Value * 2;")]); + AwaitAssert(() => rig.Driver("drv-2").SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + rig.Deploy(TwoDrivers, equip, Rev('d'), virtualTags: + [ + ("vt-1", Equipment, "Doubled", $"return (double)ctx.GetTag(\"{SpeedPath}\").Value * 2;"), + ("vt-2", Equipment, "Pressure2", "return (double)ctx.GetTag(\"Plant/Modbus2/dev2/pressure\").Value * 2;"), + ]); + // Positive control: vt-2 is a new consumer of drv-2's ref, so drv-2 is re-pushed … + AwaitAssert(() => rig.Driver("drv-2").SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct); + Thread.Sleep(300); + // … while drv-1 (c and d both skipped) stays at 2. + drv1.SubscribeCount.ShouldBe(2, "an unchanged driver was re-subscribed by a deploy that added nothing it seeds"); + } + + private static void factoryCreatedOnce(Rig rig) => + rig.Factory.Created.Count(d => d.DriverInstanceId == "drv-1").ShouldBe(1, "drv-1 must be the same kept driver throughout"); + + private static RevisionHash Rev(char c) => RevisionHash.Parse(new string(c, 64)); + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private sealed class Rig + { + private readonly RuntimeActorTestBase _kit; + private readonly IDbContextFactory _db; + private readonly IActorRef _host; + private readonly TestProbe _coordinator; + + public RecordingSubscribableDriverFactory Factory { get; } = new("Modbus"); + public volatile bool Rebuilt; + public volatile bool Degraded; + + public Rig(RuntimeActorTestBase kit, IDbContextFactory db) + { + _kit = kit; + _db = db; + _coordinator = kit.CreateTestProbe(); + var publish = kit.CreateTestProbe(); + publish.SetAutoPilot(new DelegateAutoPilot((sender, message) => + { + if (message is OpcUaPublishActor.RebuildAddressSpace { ReportOutcome: true } rebuild) + sender.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, + Degraded: Degraded, DegradedReason: Degraded ? "test degraded" : null, AddressSpaceRebuilt: Rebuilt)); + return AutoPilot.KeepRunning; + })); + _host = kit.Sys.ActorOf(DriverHostActor.Props( + _db, TestNode, _coordinator.Ref, + driverFactory: Factory, + localRoles: new HashSet { "driver" }, + dependencyMux: kit.CreateTestProbe().Ref, + opcUaPublishActor: publish.Ref, + virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: kit.CreateTestProbe().Ref)); + } + + public RecordingSubscribableDriver Driver(string id) + { + RecordingSubscribableDriver? found = null; + _kit.AwaitAssert(() => (found = Factory.Created.LastOrDefault(d => d.DriverInstanceId == id)).ShouldNotBeNull(), + PresenceBudget, cancellationToken: Ct); + return found!; + } + + public void Deploy((string, string, string, string, string, bool)[] tags, (string, string, string, string, string?)[] refs, + RevisionHash rev, (string, string, string, string)[]? virtualTags = null, bool expectDegraded = false) + { + var id = V3ArtifactSeeder.SeedV3Deployment(_db, rev, tags, refs, enabled: true, virtualTags: virtualTags); + _host.Tell(new ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.DispatchDeployment(id, rev, CorrelationId.NewId())); + var ack = _coordinator.FishForMessage( + m => m.DeploymentId == id, PresenceBudget, cancellationToken: Ct); + ack.Outcome.ShouldBe(ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.ApplyAckOutcome.Applied); + ack.Degraded.ShouldBe(expectDegraded); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs index d5edc255a..1de65334e 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs @@ -53,6 +53,8 @@ public static class V3ArtifactSeeder /// only way to express a driver that is a running child yet absent from both the value- and alarm-ref /// maps — the _children.Keys arm of ApplyDesiredSubscriptions's union, which must still /// hand that child an explicit EMPTY set rather than skipping it. + /// Optional Equipment VirtualTags (#995): each gets its own script row with + /// Source as its body; EquipmentId must name a seeded equipment (EQ-{area}-{line}-{equip}). /// The seeded deployment's id. public static DeploymentId SeedV3Deployment( IDbContextFactory db, RevisionHash rev, @@ -61,7 +63,8 @@ public static class V3ArtifactSeeder bool enabled = false, IReadOnlyDictionary? tagConfigByTag = null, string[]? taglessDrivers = null, - IReadOnlyDictionary? driverRowIds = null) + IReadOnlyDictionary? driverRowIds = null, + (string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null) { Guid RowId(string id) => driverRowIds is not null && driverRowIds.TryGetValue(id, out var g) ? g : Guid.Empty; var drivers = rawTags @@ -113,6 +116,11 @@ public static class V3ArtifactSeeder UnsLines = lines, Equipment = equipment, UnsTagReferences = unsTagReferences, + Scripts = (virtualTags ?? []).Select(v => new { ScriptId = "scr-" + v.VirtualTagId, SourceCode = v.Source }).ToArray(), + VirtualTags = (virtualTags ?? []).Select(v => new + { + v.VirtualTagId, v.EquipmentId, v.Name, DataType = "Float", ScriptId = "scr-" + v.VirtualTagId, Enabled = true, + }).ToArray(), }); var id = DeploymentId.NewId();