fix(runtime): #995 a deploy no longer re-subscribes untouched drivers, and apply-time artifact work runs once off the pinned thread

R-11: DriverHostActor skips the deploy bulk push for a kept child whose seeding
fingerprint (value refs + 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 when the address-space
outcome reports a rebuild (new additive RebuildCompleted.AddressSpaceRebuilt,
default true), degraded, timed out, or the apply threw. Boot/restore still push all.

R-14: ParsedDeploymentArtifact memoises the data projection + its validation per node
id (a throw re-thrown to every caller), and the row parsers skip it when the three data
arrays are empty. OpcUaPublishActor hashes the artifact once (RebuildAddressSpace.
ArtifactRevision) and reads the cluster redundancy mode from the plan step's parse
instead of a second parse on the pinned thread. InjectScriptSource skips JsonNode.Parse
for tag configs without a scriptId.
This commit is contained in:
Joseph Doherty
2026-12-03 11:09:42 -05:00
parent 2827a4c3bf
commit e6bfbdb6e5
9 changed files with 691 additions and 56 deletions
@@ -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;
/// <summary>
/// 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 <see cref="DataConnectionValidator.ValidateDeployed"/>.
/// <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/> 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).
/// </summary>
private readonly Dictionary<string, DataProjectionMemo> _dataProjectionByNodeId = new(StringComparer.Ordinal);
/// <summary>Diagnostics / tests (#995 R-14): how many data projections this parsed artifact actually built.</summary>
internal int DataProjectionBuilds { get; private set; }
private sealed class DataProjectionMemo
{
public (DraftSnapshot Snapshot, string ClusterId)? Projection;
public ExceptionDispatchInfo? Failure;
public IReadOnlyList<ValidationError>? Errors;
}
/// <summary>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.</summary>
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<DataConnection> 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<DataExport> 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<RemoteNamespaceMapping> 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;
}
/// <summary>The deployed-data validation of <paramref name="snapshot"/>, computed once per memoised projection.</summary>
private IReadOnlyList<ValidationError> 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<string> ids)
private void ValidateRows(DraftSnapshot snapshot, IEnumerable<string> 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);
@@ -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;
}
}
/// <summary>Gitea #995 (R-14): the <see cref="ReadClusterRedundancyMode(ReadOnlySpan{byte}, string)"/> 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.</summary>
/// <param name="parsed">The parsed artifact.</param>
/// <param name="nodeId">This node's <c>host:port</c> id.</param>
/// <returns>The mode name, or null.</returns>
internal static string? ReadClusterRedundancyMode(ParsedDeploymentArtifact parsed, string nodeId)
{
try
{
return parsed.ReadClusterRedundancyMode(nodeId);
}
catch (JsonException)
{
return null;
}
}
}
internal sealed partial class ParsedDeploymentArtifact
{
/// <summary>See <see cref="DeploymentArtifact.ReadClusterRedundancyMode(ReadOnlySpan{byte}, string)"/>.</summary>
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
{
/// <summary>
/// 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<string, string> 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; }
@@ -488,6 +488,33 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// the child the last-known-good set, not an empty one.</para></summary>
private readonly Dictionary<string, DesiredSubscriptionSet> _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).
/// <summary>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.</summary>
private readonly Dictionary<string, IActorRef> _plainPushedTo = new(StringComparer.Ordinal);
/// <summary>Per-driver seeding fingerprint from the last apply (see <see cref="SeedingFingerprint"/>).</summary>
private Dictionary<string, string[]> _seedingFingerprints = new(StringComparer.Ordinal);
/// <summary>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.</summary>
private HashSet<string>? _consumerRefs;
/// <summary>The <see cref="IDependencyConsumer"/> drivers hosted here, keyed like <see cref="_depConsumerAdapters"/>.</summary>
private readonly Dictionary<string, IDependencyConsumer> _depConsumers = new(StringComparer.Ordinal);
/// <summary>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).</summary>
private readonly Dictionary<CorrelationId, HashSet<string>> _seedAfterAddressSpace = new();
/// <summary>
/// Cached local <see cref="RedundancyRole"/> from the latest <see cref="RedundancyStateChanged"/>
/// 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<string>(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
/// </summary>
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
/// </summary>
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
/// </remarks>
/// <param name="deploymentId">The deployment being applied — diagnostics only.</param>
/// <param name="parsed">The apply's parsed artifact.</param>
private void PushDesiredSubscriptionsFromParsed(DeploymentId deploymentId, ParsedDeploymentArtifact parsed)
/// <param name="skipUnchanged">#995 R-11: the deploy path skips the re-subscribe of a driver with nothing
/// seedable changed (see <see cref="ApplyDesiredSubscriptions"/>).</param>
/// <returns>The drivers whose re-subscribe was skipped (empty unless <paramref name="skipUnchanged"/>).</returns>
private IReadOnlyCollection<string> 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<string>();
}
ApplyDesiredSubscriptions(composition);
return ApplyDesiredSubscriptions(composition, skipUnchanged);
}
/// <summary>Gets (creating on first use) the per-driver bucket of a secondary index.</summary>
@@ -4125,7 +4167,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// Equipment VirtualTag + ScriptedAlarm plans to their hosts.
/// </summary>
/// <param name="composition">The composition this node should serve.</param>
private void ApplyDesiredSubscriptions(AddressSpaceComposition composition)
/// <param name="skipUnchanged">
/// #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.
/// </param>
/// <returns>The drivers whose push was skipped.</returns>
private IReadOnlyCollection<string> 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<string>());
}
// #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<string, string[]>(StringComparer.Ordinal);
foreach (var driverId in _desiredByDriver.Keys)
_seedingFingerprints[driverId] = SeedingFingerprint(driverId, composition);
var previousConsumerRefs = _consumerRefs;
_consumerRefs = ConsumerRefs(composition);
HashSet<string>? newConsumerRefs = null;
if (previousConsumerRefs is not null)
{
newConsumerRefs = new HashSet<string>(_consumerRefs, StringComparer.Ordinal);
newConsumerRefs.ExceptWith(previousConsumerRefs);
}
var total = 0;
List<string>? skipped = null;
foreach (var (driverId, entry) in _children)
{
if (skipUnchanged && CanSkipResubscribe(driverId, entry.Actor, previousFingerprints, newConsumerRefs))
{
(skipped ??= new List<string>()).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<string>?)skipped ?? Array.Empty<string>();
}
/// <summary>
/// #995 R-11: whether the deploy push to <paramref name="driverId"/> 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 (<see cref="SeedingFingerprint"/>), 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.
/// </summary>
private bool CanSkipResubscribe(string driverId, IActorRef child, Dictionary<string, string[]> previousFingerprints,
HashSet<string>? 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;
}
/// <summary>
/// #995 R-11: everything a deploy re-subscribe of <paramref name="driverId"/> 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.
/// </summary>
private string[] SeedingFingerprint(string driverId, AddressSpaceComposition composition)
{
var set = _desiredByDriver[driverId];
var historized = new Dictionary<string, string>(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<string>(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();
}
/// <summary>#995 R-11: every ref a mux consumer reads under <paramref name="composition"/> — enabled VirtualTags,
/// enabled scripted alarms and the hosted dependency-consuming drivers (read after the apply's reconcile).</summary>
private HashSet<string> ConsumerRefs(AddressSpaceComposition composition)
{
var refs = new HashSet<string>(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;
}
/// <summary>#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.</summary>
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);
}
/// <summary>
@@ -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.</summary>
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);
@@ -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.
/// </param>
/// <param name="ArtifactRevision">
/// Gitea #995 (R-14): SHA-256 (lower hex) of <see cref="Artifact"/>, 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.
/// </param>
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);
/// <summary>
/// the reply to a <see cref="RebuildAddressSpace"/> carrying
@@ -156,8 +161,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// stale. An empty plan (nothing changed) is clean.
/// </param>
/// <param name="DegradedReason">A short operator-readable reason; null when clean.</param>
/// <param name="AddressSpaceRebuilt">
/// Gitea #995 (R-11): <see langword="false"/> only when the apply was a clean NON-rebuild — every node that
/// existed before it still exists with its value. <c>DriverHostActor</c> skips the re-subscribe of a driver
/// whose desired set and fan-out are unchanged, and re-pushes those drivers when this is <see langword="true"/>
/// (a full rebuild recreated their nodes without a value). Defaults to <see langword="true"/> — the
/// conservative answer for any producer that does not know.
/// </param>
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<string> Inconsistencies);
AddressSpaceComposition Composition, AddressSpacePlan Plan, IReadOnlyList<string> Inconsistencies,
string? ClusterRedundancyMode = null);
/// <summary>The off-thread parse / plan step threw (unreadable bytes, a composer fault).</summary>
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);
/// <summary>Test seams for the off-thread plan step. Production passes none.</summary>
internal sealed class TestHooks
@@ -189,6 +204,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
internal Action? BeforePlan { get; init; }
internal Action? BeforeComposition { get; init; }
/// <summary>#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.</summary>
internal Action<int>? OnRedundancyModeRead { get; init; }
/// <summary>Replaces <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/> (a test makes it throw).</summary>
internal Func<ParsedDeploymentArtifact, string, DataPlaneAuthorityProjection>? 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)));
/// <summary>Produces the actor through its internal (seam-carrying) constructor, for <see cref="PropsForTests(IOpcUaAddressSpaceSink, AddressSpaceApplier?, TestHooks?, int, NodeId?, IDataPlaneAuthoritySink?)"/>.</summary>
@@ -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);
}
/// <summary>#995 R-14: stamp the request with its artifact's SHA-256 (or "unavailable"), unless it already carries it.</summary>
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<object>(() =>
@@ -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));
}
/// <summary>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
/// <param name="projection">The keys + grants decoded (off-thread) from the rebuild's single parse of the artifact.</param>
/// <param name="artifactBytes">The RAW artifact bytes — hashed for the revision id, which must be
/// SHA-256 of the exact blob (see below); never re-parsed here.</param>
private void FeedDataPlaneAuthority(DataPlaneAuthorityProjection projection, byte[] artifactBytes)
/// <param name="revision">#995 R-14: the request's already-computed SHA-256 of <paramref name="artifactBytes"/>; hashed
/// here only when absent.</param>
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 <c>otopcua.redundancy.mode_mismatch</c>. The node keeps its local mode — the only value available
/// before SDK start. <c>Unset</c> has opted out and is not checked.
/// </summary>
/// <param name="artifact">The applied artifact bytes.</param>
private void CheckRedundancyMode(byte[] artifact)
/// <param name="clusterMode">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.</param>
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);
}
/// <summary>Whether the #717 deploy-time redundancy-mode cross-check applies on this node.</summary>
private bool WantsRedundancyModeCheck() => _redundancy.Mode != OpcUaRedundancyMode.Unset && _localNode is not null;
/// <summary>The applier-less (dev) path's synchronous redundancy-mode read; never throws.</summary>
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));
/// <summary>The legacy role-only ServiceLevel switch (primary-leader → 240, primary → 200,