fix(runtime): #1054 the artifact hash moves off the OPC UA pinned thread; new mux readers are guarded into ConsumerRefs

#995 follow-up 1: OpcUaPublishActor still SHA-256'd every rebuild's artifact once on its pinned
thread (WithArtifactRevision). DriverHostActor already hashes the same bytes for its catalog
attempt, so it now stamps RebuildAddressSpace.ArtifactRevision at all three send sites (deploy
apply, boot-from-cache, bootstrap restore) from a per-blob ConditionalWeakTable memo (one hash
per blob instance, no lifetime extension). The publish actor's fallback hash stays for unstamped
senders and is observable through TestHooks.OnArtifactHashed.

#995 follow-up 2: DependencyMuxConsumerRegistrationGuardTests scans src for every
DependencyMuxActor.RegisterInterest sender; an unlisted one fails with the instruction to fold
its refs into DriverHostActor.ConsumerRefs, and each listed replay-opting consumer's composition
term must still appear in ConsumerRefs (mutation-checked). The historization recorder is the one
exempt, non-replay registrant.
This commit is contained in:
Joseph Doherty
2026-12-03 15:10:24 -05:00
parent 186b5d696d
commit e967042fbb
8 changed files with 181 additions and 17 deletions
+2 -1
View File
@@ -289,7 +289,8 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
re-pushed after the address-space outcome if it was a rebuild (`RebuildCompleted.AddressSpaceRebuilt`), degraded,
timed out, or the apply threw. `AddressSpaceRebuilt` is also set for a repair pass and for any apply after a
degraded one — those create nodes the degraded apply missed, valueless, whose drivers the deploy skipped.
A new mux value consumer must join `DriverHostActor.ConsumerRefs`.
A new mux value consumer must join `DriverHostActor.ConsumerRefs` — `DependencyMuxConsumerRegistrationGuardTests`
(#1054) fails on any unlisted `RegisterInterest` sender in `src`.
`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
+4 -1
View File
@@ -273,7 +273,10 @@ Things to know before touching any of this:
skips its driver (fingerprint unchanged) — without the re-push the node stayed `BadWaitingForInitialData` until its
value changed, forever for a constant. Pinned against a real publish actor by `DriverHostActorDegradedRepairReseedTests`.
⚠️ 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.
join `ConsumerRefs`, or its first deploy leaves it waiting for the next value change. Enforced since #1054 by
`DependencyMuxConsumerRegistrationGuardTests`: every `src` site that sends `DependencyMuxActor.RegisterInterest`
must be in its table, and each replay-opting one's composition term must appear in `ConsumerRefs` (the
historization recorder is the one exempt, non-replay registrant).
- ⚠️ **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
@@ -1801,7 +1801,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
throw;
}
_opcUaPublishActor?.Tell(
new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, blob, CatalogAttempt: _catalogAttempt));
new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, blob, CatalogAttempt: _catalogAttempt,
ArtifactRevision: ArtifactRevisionOf(blob)));
if (_opcUaPublishActor is null && _catalogAttempt is not null)
_catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: true);
return true;
@@ -3427,7 +3428,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_currentRevision = msg.Revision;
AwaitAddressSpaceOutcomeThenAck(msg.DeploymentId, msg.Revision, msg.Correlation, catalogFailed);
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(
msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true, CatalogAttempt: _catalogAttempt));
msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true, CatalogAttempt: _catalogAttempt,
ArtifactRevision: ArtifactRevisionOf(appliedBlob)));
// Reaching here means the artifact came from central, so the node is no longer serving a
// cache-sourced configuration. Note this only clears on a real apply: a dispatch of the
// revision already booted from cache short-circuits in HandleDispatchFromSteady without
@@ -3818,10 +3820,26 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
return blob;
}
/// <summary>
/// Gitea #1054: the SHA-256 of each artifact blob this host hashed, keyed by the blob INSTANCE (weakly — it never
/// extends a multi-MB artifact's lifetime). <see cref="BeginCatalogAttempt"/> hashes the apply's bytes anyway; the
/// <see cref="OpcUa.OpcUaPublishActor.RebuildAddressSpace"/> sent for the same bytes carries that hash
/// (<see cref="ArtifactRevisionOf"/>), so the publish actor's pinned OPC UA thread no longer hashes the artifact.
/// </summary>
private readonly System.Runtime.CompilerServices.ConditionalWeakTable<byte[], string> _artifactRevisions = new();
/// <summary>Gitea #1054: the lower-hex SHA-256 of <paramref name="blob"/> (<c>"unavailable"</c> for no bytes),
/// computed at most once per blob instance on THIS actor's thread.</summary>
/// <param name="blob">The artifact bytes.</param>
/// <returns>The revision string the publish actor and the catalog attempt both use.</returns>
private string ArtifactRevisionOf(byte[]? blob) =>
blob is not { Length: > 0 }
? "unavailable"
: _artifactRevisions.GetValue(blob, static b => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(b)));
private void BeginCatalogAttempt(byte[]? blob)
{
var revision = blob is { Length: > 0 }
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(blob)) : "unavailable";
var revision = ArtifactRevisionOf(blob);
_dataConnections?.BeginAttempt(revision);
if (_catalogCoordinator is null) return;
_catalogAttempt = _catalogCoordinator.BeginAttempt(revision);
@@ -4083,7 +4101,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// it. (Found on the docker-dev live gate.)
if (revision is { } rev)
CacheAppliedArtifact(deploymentId, rev, appliedBlob);
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, appliedBlob, CatalogAttempt: _catalogAttempt));
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, appliedBlob, CatalogAttempt: _catalogAttempt,
ArtifactRevision: ArtifactRevisionOf(appliedBlob)));
_log.Info("DriverHost {Node}: restored served state for applied deployment {Id} on bootstrap", _localNode, deploymentId);
}
catch (Exception ex)
@@ -140,9 +140,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// 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.
/// Gitea #995 (R-14): SHA-256 (lower hex) of <see cref="Artifact"/> (or <c>"unavailable"</c> for no bytes), 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. Gitea #1054: <c>DriverHostActor</c> stamps it (it already
/// hashed the same bytes for its catalog attempt), so the pinned thread hashes nothing; the actor computes it once
/// itself only for a sender that leaves it null (tests, any future caller). It MUST be the hash of
/// <see cref="Artifact"/>'s exact bytes — it is the authority revision a node recognises a re-applied deployment by.
/// </param>
public sealed record RebuildAddressSpace(
CorrelationId Correlation, DeploymentId? DeploymentId = null, byte[]? Artifact = null,
@@ -211,6 +214,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// assert it ran on the plan step rather than the actor thread.</summary>
internal Action<int>? OnRedundancyModeRead { get; init; }
/// <summary>#1054: observes every artifact SHA-256 the actor computes itself (the hashing thread's managed id) — a
/// request that arrives already stamped must cause none.</summary>
internal Action<int>? OnArtifactHashed { get; init; }
/// <summary>Replaces <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/> (a test makes it throw).</summary>
internal Func<ParsedDeploymentArtifact, string, DataPlaneAuthorityProjection>? ParseAuthority { get; init; }
}
@@ -922,13 +929,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
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",
};
/// <summary>#995 R-14: stamp the request with its artifact's SHA-256 (or "unavailable"), unless it already carries it
/// — which every production request does since #1054 (<c>DriverHostActor</c> stamps it), so this fallback hash on the
/// pinned thread runs only for an unstamped sender.</summary>
private RebuildAddressSpace WithArtifactRevision(RebuildAddressSpace msg)
{
if (msg.ArtifactRevision is not null) return msg;
if (msg.Artifact is not { Length: > 0 } bytes) return msg with { ArtifactRevision = "unavailable" };
_hooks?.OnArtifactHashed?.Invoke(Environment.CurrentManagedThreadId);
return msg with { ArtifactRevision = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)) };
}
private void StageStandaloneCatalog(RebuildAddressSpace msg, ParsedDeploymentArtifact parsed)
{
@@ -0,0 +1,102 @@
using System.Text.RegularExpressions;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Gitea #1054 (#995 follow-up). Since #995 R-11 a deploy skips re-subscribing a kept driver whose seeding fingerprint
/// is unchanged, unless one of its value refs ENTERED <c>DriverHostActor.ConsumerRefs</c> — the set of refs some mux
/// value consumer reads. The mux replays a retained value only for refs a replay-opting subscriber already named, so
/// a NEW kind of consumer that registers replay interest with the mux but is not folded into <c>ConsumerRefs</c> gets
/// no first value on its first deploy: it waits for the next value change, which for a static input never comes.
/// <para>
/// This guard makes that rule structural. Every production site that sends
/// <c>DependencyMuxActor.RegisterInterest</c> must be a known consumer, and every known replay-opting consumer must
/// have its composition term in <c>ConsumerRefs</c>. A new site fails here with the instruction to do both.
/// </para>
/// </summary>
public sealed class DependencyMuxConsumerRegistrationGuardTests
{
/// <summary>
/// Every production registrant, keyed by file name, with the token its refs appear under in
/// <c>DriverHostActor.ConsumerRefs</c> — or null for a registrant that deliberately does NOT need a seed.
/// </summary>
private static readonly IReadOnlyDictionary<string, string?> KnownRegistrants = new Dictionary<string, string?>(StringComparer.Ordinal)
{
// Enabled VirtualTags' DependencyRefs.
["VirtualTagActor.cs"] = "composition.EquipmentVirtualTags",
// Enabled scripted alarms' DependencyRefs.
["ScriptedAlarmHostActor.cs"] = "composition.EquipmentScriptedAlarms",
// Every hosted IDependencyConsumer driver (Calculation) — the adapter registers on its behalf.
["DependencyConsumerMuxAdapter.cs"] = "_depConsumers",
// The historization recorder registers WITHOUT replay and records changes only: a seed would be a duplicate
// sample, and the mux retains nothing on its behalf. Exempt by design (#995 R-11).
["ContinuousHistorizationRecorder.cs"] = null,
};
private static readonly Regex Registration = new(@"new\s+(?:DependencyMuxActor\.)?RegisterInterest\s*\(", RegexOptions.Compiled);
[Fact]
public void Every_mux_registrant_is_known_and_every_replay_registrant_feeds_ConsumerRefs()
{
var src = Path.Combine(RepoRoot().FullName, "src");
var registrants = Directory.EnumerateFiles(src, "*.cs", SearchOption.AllDirectories)
.Where(f => !IsBuildOutput(f))
.Where(f => Path.GetFileName(f) != "DependencyMuxActor.cs") // the record's own declaration
.Where(f => Registration.IsMatch(StripComments(File.ReadAllText(f))))
.Select(Path.GetFileName)
.ToHashSet(StringComparer.Ordinal);
// Positive control: the scan really finds the registrants it is supposed to police.
registrants.ShouldContain("VirtualTagActor.cs", "the source scan found no registrants at all — the guard would pass vacuously");
foreach (var file in registrants)
KnownRegistrants.ContainsKey(file!).ShouldBeTrue(
$"{file} registers interest with the dependency mux but is not a known consumer. If it reads driver values " +
"and needs a first value, fold its refs into DriverHostActor.ConsumerRefs (else a deploy that skips the " +
"kept driver's re-subscribe leaves it waiting for the next value change), then list it here.");
var consumerRefs = ConsumerRefsBody();
foreach (var (file, token) in KnownRegistrants)
{
registrants.ShouldContain(file, $"{file} no longer registers with the mux — drop it from this guard's table");
if (token is not null)
consumerRefs.ShouldContain(token, Case.Sensitive,
$"{file} is a replay-opting mux consumer, but DriverHostActor.ConsumerRefs no longer reads {token}");
}
}
/// <summary>The body of <c>DriverHostActor.ConsumerRefs</c>, comments stripped.</summary>
private static string ConsumerRefsBody()
{
var path = Directory.EnumerateFiles(Path.Combine(RepoRoot().FullName, "src"), "DriverHostActor.cs", SearchOption.AllDirectories)
.Single(f => !IsBuildOutput(f));
var text = StripComments(File.ReadAllText(path));
var start = text.IndexOf("HashSet<string> ConsumerRefs(AddressSpaceComposition composition)", StringComparison.Ordinal);
start.ShouldBeGreaterThanOrEqualTo(0, "DriverHostActor.ConsumerRefs not found — update this guard to its new shape");
var open = text.IndexOf('{', start);
var depth = 0;
for (var i = open; i < text.Length; i++)
{
if (text[i] == '{') depth++;
else if (text[i] == '}' && --depth == 0) return text[open..(i + 1)];
}
throw new InvalidOperationException("unbalanced braces in DriverHostActor.ConsumerRefs");
}
private static string StripComments(string code) =>
Regex.Replace(code, @"//[^\n]*|/\*.*?\*/", string.Empty, RegexOptions.Singleline);
private static DirectoryInfo RepoRoot()
{
var root = new DirectoryInfo(AppContext.BaseDirectory);
while (root is not null && !File.Exists(Path.Combine(root.FullName, "ZB.MOM.WW.OtOpcUa.slnx"))) root = root.Parent;
root.ShouldNotBeNull("could not find the repo root");
return root;
}
private static bool IsBuildOutput(string file) =>
file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}") ||
file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}");
}
@@ -93,6 +93,30 @@ public sealed class DeploymentArtifactApplyCostTests : RuntimeActorTestBase
lock (readThreads) readThreads.ShouldBe([Volatile.Read(ref planThread)], "one read, on the plan step's thread");
}
/// <summary>Gitea #1054: a rebuild that arrives stamped with its artifact's revision (as every <c>DriverHostActor</c>
/// send now is) is not hashed again on the publish actor's pinned thread; an unstamped one is hashed once (the
/// positive control — the hook does observe the fallback).</summary>
[Fact]
public void A_stamped_rebuild_is_not_hashed_on_the_publish_actor_and_an_unstamped_one_is_hashed_once()
{
var hashes = 0;
var hooks = new OpcUaPublishActor.TestHooks { OnArtifactHashed = _ => Interlocked.Increment(ref hashes) };
var sink = new NullSink();
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks, localNode: NodeId.Parse("x:1")));
var artifact = Encoding.UTF8.GetBytes("{\"Clusters\":[],\"Nodes\":[]}");
var revision = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(artifact));
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact,
ReportOutcome: true, ArtifactRevision: revision));
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
Volatile.Read(ref hashes).ShouldBe(0, "the stamped revision must be reused, not recomputed on the pinned thread");
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact, ReportOutcome: true));
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
Volatile.Read(ref hashes).ShouldBe(1, "an unstamped request is hashed exactly once");
}
private sealed class NullSink : IOpcUaAddressSpaceSink
{
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime ts, AddressSpaceRealm realm) { }
@@ -103,6 +103,8 @@ public sealed class DriverHostActorBootFromCacheTests : RuntimeActorTestBase
var rebuild = publishProbe.ExpectMsg<OpcUaPublishActor.RebuildAddressSpace>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
rebuild.Artifact.ShouldNotBeNull();
rebuild.Artifact.ShouldBe(blob);
// Gitea #1054: the boot-from-cache rebuild is stamped too (no hash on the publish actor's pinned thread).
rebuild.ArtifactRevision.ShouldBe(Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(blob)));
}
[Theory]
@@ -42,6 +42,9 @@ public sealed class DriverHostActorDegradedAckTests : RuntimeActorTestBase
var rebuild = publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
rebuild.ReportOutcome.ShouldBeTrue();
// Gitea #1054: the host stamps the artifact's SHA-256 so the publish actor's pinned thread hashes nothing.
rebuild.Artifact.ShouldNotBeNull();
rebuild.ArtifactRevision.ShouldBe(Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(rebuild.Artifact)));
// The ack is HELD until the outcome lands — the pre-#601 code had already sent it by now.
coordinator.ExpectNoMsg(TimeSpan.FromMilliseconds(300), TestContext.Current.CancellationToken);