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
@@ -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;
/// <summary>
/// Gitea #995 (review 2026-12-02 R-14): apply-time artifact work was repeated. The data projection (a full
/// deserialise of every topology table + <c>ValidateDeployed</c>) ran three times inside
/// <c>ParseDataPlaneAuthority</c> 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.
/// </summary>
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<InvalidDataException>(() => parsed.ParseDataExports("node-a"));
Should.Throw<InvalidDataException>(() => 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<int>();
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<AddressSpaceApplier>.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<OpcUaPublishActor.RebuildCompleted>(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<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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 = [];
/// <summary>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).</summary>
[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);
}
/// <summary>A full rebuild recreates every node without a value: the skipped driver is re-pushed once the
/// address-space outcome reports the rebuild.</summary>
[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);
}
/// <summary>A degraded apply may have left nodes missing: re-push too.</summary>
[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);
}
/// <summary>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.</summary>
[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<OtOpcUaConfigDbContext> _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<OtOpcUaConfigDbContext> 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<string> { "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<ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.ApplyAck>(
m => m.DeploymentId == id, PresenceBudget, cancellationToken: Ct);
ack.Outcome.ShouldBe(ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.ApplyAckOutcome.Applied);
ack.Degraded.ShouldBe(expectDegraded);
}
}
}
@@ -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 <c>_children.Keys</c> arm of <c>ApplyDesiredSubscriptions</c>'s union, which must still
/// hand that child an explicit EMPTY set rather than skipping it.</param>
/// <param name="virtualTags">Optional Equipment VirtualTags (#995): each gets its own script row with
/// <c>Source</c> as its body; <c>EquipmentId</c> must name a seeded equipment (<c>EQ-{area}-{line}-{equip}</c>).</param>
/// <returns>The seeded deployment's id.</returns>
public static DeploymentId SeedV3Deployment(
IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev,
@@ -61,7 +63,8 @@ public static class V3ArtifactSeeder
bool enabled = false,
IReadOnlyDictionary<string, string>? tagConfigByTag = null,
string[]? taglessDrivers = null,
IReadOnlyDictionary<string, Guid>? driverRowIds = null)
IReadOnlyDictionary<string, Guid>? 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();