diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index 4c267ace9..dcf7fc11b 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -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 diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 31bc628fd..bfd1ade7a 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -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 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 f8f85c14a..db0226f3d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -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; } + /// + /// 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). hashes the apply's bytes anyway; the + /// sent for the same bytes carries that hash + /// (), so the publish actor's pinned OPC UA thread no longer hashes the artifact. + /// + private readonly System.Runtime.CompilerServices.ConditionalWeakTable _artifactRevisions = new(); + + /// Gitea #1054: the lower-hex SHA-256 of ("unavailable" for no bytes), + /// computed at most once per blob instance on THIS actor's thread. + /// The artifact bytes. + /// The revision string the publish actor and the catalog attempt both use. + 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) 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 ab889efda..6f76bcec5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -140,9 +140,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// 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. + /// Gitea #995 (R-14): SHA-256 (lower hex) of (or "unavailable" 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: DriverHostActor 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 + /// 's exact bytes — it is the authority revision a node recognises a re-applied deployment by. /// 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. internal Action? OnRedundancyModeRead { get; init; } + /// #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. + internal Action? OnArtifactHashed { get; init; } + /// Replaces (a test makes it throw). internal Func? ParseAuthority { get; init; } } @@ -922,13 +929,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers 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", - }; + /// #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 (DriverHostActor stamps it), so this fallback hash on the + /// pinned thread runs only for an unstamped sender. + 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) { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DependencyMuxConsumerRegistrationGuardTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DependencyMuxConsumerRegistrationGuardTests.cs new file mode 100644 index 000000000..bc836d4dd --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DependencyMuxConsumerRegistrationGuardTests.cs @@ -0,0 +1,102 @@ +using System.Text.RegularExpressions; +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// 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 DriverHostActor.ConsumerRefs — 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 ConsumerRefs gets +/// no first value on its first deploy: it waits for the next value change, which for a static input never comes. +/// +/// This guard makes that rule structural. Every production site that sends +/// DependencyMuxActor.RegisterInterest must be a known consumer, and every known replay-opting consumer must +/// have its composition term in ConsumerRefs. A new site fails here with the instruction to do both. +/// +/// +public sealed class DependencyMuxConsumerRegistrationGuardTests +{ + /// + /// Every production registrant, keyed by file name, with the token its refs appear under in + /// DriverHostActor.ConsumerRefs — or null for a registrant that deliberately does NOT need a seed. + /// + private static readonly IReadOnlyDictionary KnownRegistrants = new Dictionary(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}"); + } + } + + /// The body of DriverHostActor.ConsumerRefs, comments stripped. + 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 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}"); +} 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 index 8b46546ed..516050a65 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DeploymentArtifactApplyCostTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DeploymentArtifactApplyCostTests.cs @@ -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"); } + /// Gitea #1054: a rebuild that arrives stamped with its artifact's revision (as every DriverHostActor + /// 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). + [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.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(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(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) { } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorBootFromCacheTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorBootFromCacheTests.cs index 033c22934..13a626328 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorBootFromCacheTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorBootFromCacheTests.cs @@ -103,6 +103,8 @@ public sealed class DriverHostActorBootFromCacheTests : RuntimeActorTestBase var rebuild = publishProbe.ExpectMsg(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] diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDegradedAckTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDegradedAckTests.cs index 0875d1755..df4b5ef75 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDegradedAckTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDegradedAckTests.cs @@ -42,6 +42,9 @@ public sealed class DriverHostActorDegradedAckTests : RuntimeActorTestBase var rebuild = publish.FishForMessage(_ => 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);