From 186b5d696d52dc20f960bcf28fd25551052a1351 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:10:17 -0500 Subject: [PATCH 1/3] fix(opcua): #1041 a device confirmation arriving after a newer write's revert lands instead of being dropped #979 follow-up 1: write A then B, B refused first (node reverts to the pre-A value P), the device confirms A afterwards. The revert closed the overlap window and A's success was dropped as an outcome from a closed window, so the node showed P while the device held A until the next driver publication. EquipmentVariableState.CloseWindowAfterRevert now keeps the window's still-pending older attempts (bounded like the window, carried across later reverts above the confirmed floor); a late success of one lands its tuple (LateConfirm) when nothing touched the node since the revert, or becomes the confirmed tuple of a window opened since. A driver publication or a newer owner's success discards them. #979 follow-up 2 (dependents keep last value during operator Restart / config respawn): not a defect - the stopped child's PostStop comms-loss fan (03/S15) reaches the dependency mux and hands dependents BadNoCommunication until the new driver object publishes. Pinned by two new DriverHostActorSourceRemovedTests (identical-value recovery); mutation-checked: removing the PostStop ConnectivityChanged fails both. --- docs/ReadWriteOperations.md | 7 ++ .../EquipmentVariableState.cs | 69 +++++++++++++++++++ .../OtOpcUaNodeManager.cs | 17 ++++- .../Sdk2EquipmentVariableTests.cs | 67 ++++++++++++++++++ .../DriverHostActorSourceRemovedTests.cs | 48 +++++++++++++ 5 files changed, 207 insertions(+), 1 deletion(-) diff --git a/docs/ReadWriteOperations.md b/docs/ReadWriteOperations.md index 13cf5aded..5b098942a 100644 --- a/docs/ReadWriteOperations.md +++ b/docs/ReadWriteOperations.md @@ -156,6 +156,13 @@ either completion order) leave the node on its pre-A value and status, never on audit event's `OldValue` reports that confirmed value. Each NodeId — the raw node and every UNS mirror — keeps its own window; a write through one never touches the other, and both receive the next fan-out publish. + +A confirmation that arrives AFTER a newer write's refusal already reverted the node is not dropped (#1041). +The window's older attempts still pending at the revert stay eligible: if the device then confirms one, it +holds that value, so the node shows it (Good, the attempt's timestamp) when nothing has touched the node +since the revert; if a newer write owns the node by then, the confirmation becomes that window's confirmed +tuple, so a refusal of the newer write reverts to it. A driver publication, or the success of a newer +write, discards them — the node then holds something newer than any of them. `WriteTune` and `WriteConfigure` are not separate tag-classification gates on this Value-write path. ## Remote write outcomes diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/EquipmentVariableState.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/EquipmentVariableState.cs index 702bdb51a..d84fef680 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/EquipmentVariableState.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/EquipmentVariableState.cs @@ -29,6 +29,14 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock private NodeTuple? _confirmed; private long _confirmedToken; + // Gitea #1041 (#979 follow-up): attempts still pending when their window closed by a REVERT. A refused newer + // attempt reverts the node to the confirmed tuple, but an older attempt the device has not answered yet may still + // succeed — and then the device holds ITS value. Kept here (bounded like the window) so that late confirmation can + // land: shown on the node when nothing newer touched it since the revert, or advancing the confirmed tuple of a + // window opened since. A driver publication or the owner's success clears them (the node then holds a newer truth). + private readonly SortedDictionary _revertedAttempts = new(); + private long _revertedRevision = -1; + internal readonly record struct WriteStamp(EquipmentVariableState Owner, long Token); /// One (value, status, source timestamp) tuple of the node. @@ -43,6 +51,10 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock Revert, /// A failure superseded by a newer attempt or a driver publication. Superseded, + /// #1041: a success of an attempt whose window a newer attempt's refusal already reverted, with nothing + /// newer on the node since — the device holds this attempt's value: show it + /// (). + LateConfirm, } internal WriteStamp? ActiveWriteStamp => _activeWriteToken is { } token ? new(this, token) : null; @@ -59,6 +71,40 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock _windowAttempts.Clear(); _confirmed = null; _confirmedToken = 0; + _revertedAttempts.Clear(); + } + + /// + /// #1041: closes the window after the owning attempt was refused and the node reverted + /// (caller holds ownerLock and writes the confirmed tuple to the node next). Every OLDER attempt of the window + /// that the device has not answered yet — and that is newer than what the window already confirmed — stays eligible + /// for a late confirmation (see ), together with such attempts left over from earlier + /// reverts. + /// + internal void CloseWindowAfterRevert(long failedToken) + { + var floor = _confirmedToken; + var survivors = _windowAttempts.Where(kv => kv.Key < failedToken && kv.Key > floor) + .Concat(_revertedAttempts.Where(kv => kv.Key > floor)).ToArray(); + InvalidateWriteOwnership(); + foreach (var (token, tuple) in survivors) _revertedAttempts[token] = tuple; + while (_revertedAttempts.Count > MaxWindowAttempts) _revertedAttempts.Remove(_revertedAttempts.Keys.First()); + _revertedRevision = _mutationRevision; + } + + /// #1041: lands a tuple on the node (caller holds + /// ownerLock and notifies subscribers). A still-pending NEWER reverted attempt can follow it the same way. + internal void ApplyLateConfirmation(NodeTuple confirmed) + { + _mutationRevision++; + SetTuple(confirmed.Value, confirmed.Status, confirmed.Timestamp); + _revertedRevision = _mutationRevision; + } + + private void DropRevertedThrough(long token) + { + while (_revertedAttempts.Count > 0 && _revertedAttempts.Keys.First() <= token) + _revertedAttempts.Remove(_revertedAttempts.Keys.First()); } internal void PublishValue(Variant value, StatusCode status, DateTimeUtc timestamp) @@ -88,14 +134,37 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock _windowAttempts.Clear(); _confirmed = null; _confirmedToken = 0; + // Every reverted attempt is older than the owner the device just confirmed. + _revertedAttempts.Clear(); } else if (inWindow && stamp.Token > _confirmedToken) { _confirmed = attempted; _confirmedToken = stamp.Token; } + else if (_revertedAttempts.Remove(stamp.Token, out var late)) + { + // #1041: the device confirmed an attempt after a newer one's refusal reverted the node. Anything older + // still pending can no longer be the device's last accepted write. + DropRevertedThrough(stamp.Token); + if (_committedWriteToken is not null) + { + // A newer attempt owns the node: this is the device's state underneath it, so a refusal of that + // attempt must land here rather than on the pre-revert tuple. + if (stamp.Token > _confirmedToken) + { + _confirmed = late; + _confirmedToken = stamp.Token; + } + return WriteOutcomeAction.None; + } + if (_mutationRevision != _revertedRevision) return WriteOutcomeAction.None; + confirmed = late; + return WriteOutcomeAction.LateConfirm; + } return WriteOutcomeAction.None; } + _revertedAttempts.Remove(stamp.Token); if (!owner || _confirmed is not { } settled) return WriteOutcomeAction.Superseded; confirmed = settled; return WriteOutcomeAction.Revert; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index dfa68f3ce..2b04f36f9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -4072,6 +4072,16 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage _logger.LogDebug("OtOpcUaNodeManager: device confirmed write for {NodeId}", nodeId); return; } + if (action == EquipmentVariableState.WriteOutcomeAction.LateConfirm && variable is EquipmentVariableState late) + { + // Gitea #1041: a newer attempt's refusal reverted the node before the device confirmed this older + // one, and nothing has touched the node since — the device holds this value, so show it now instead + // of leaving the reverted tuple until the next driver publication. + late.ApplyLateConfirmation(confirmed); + variable.ClearChangeMasks(SystemContext, includeChildren: false); + _logger.LogDebug("OtOpcUaNodeManager: device confirmed write for {NodeId} after a newer write's revert; landed it", nodeId); + return; + } if (action == EquipmentVariableState.WriteOutcomeAction.Superseded) { _logger.LogDebug("OtOpcUaNodeManager: ignored superseded write outcome for {NodeId}", nodeId); @@ -4095,7 +4105,12 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage variable.ClearChangeMasks(SystemContext, includeChildren: false); // notify — the Bad blip var prior = restoreValue ?? SdkValueBoundary.FromClr(priorValue, variable.DataType == DataTypeIds.Byte && variable.ValueRank == ValueRanks.OneDimension); - if (variable is EquipmentVariableState restored) restored.InvalidateWriteOwnership(); + if (variable is EquipmentVariableState restored) + { + // #1041: a stamped revert keeps the window's still-pending older attempts eligible for a late landing. + if (writeStamp is { } revertedStamp) restored.CloseWindowAfterRevert(revertedStamp.Token); + else restored.InvalidateWriteOwnership(); + } variable.Value = prior; variable.StatusCode = priorStatus; variable.Timestamp = restoreTimestamp ?? now; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/Sdk2EquipmentVariableTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/Sdk2EquipmentVariableTests.cs index 36ee62dca..0b42b9c01 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/Sdk2EquipmentVariableTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/Sdk2EquipmentVariableTests.cs @@ -373,6 +373,73 @@ public sealed class Sdk2EquipmentVariableTests : IAsyncLifetime node.StatusCode.ShouldBe(StatusCodes.Good); } + /// + /// Gitea #1041 (#979 follow-up): B (newer) is refused FIRST — the node reverts to the pre-A value P — and the + /// device confirms A only afterwards. The device now holds A, so the node must show A (Good), not stay on P until + /// the next driver publication. Before the fix the revert closed the overlap window and A's confirmation was + /// dropped as an outcome "from a closed window". + /// + [Theory] + [InlineData(AddressSpaceRealm.Raw)] + [InlineData(AddressSpaceRealm.Uns)] + public async Task A_device_confirmation_arriving_after_the_revert_lands_the_confirmed_value(AddressSpaceRealm realm) + { + var node = Node("Int32", realm: realm); + var pStamp = new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc); + _manager.WriteValue("v", 7, OpcUaStatus.Good, pStamp, realm); + var pending = PendingOutcomes(); + + Write(node, 41).ShouldBe(ServiceResult.Good); // A + Write(node, 42).ShouldBe(ServiceResult.Good); // B + pending[1].SetResult(new NodeWriteOutcome(false, "B refused")); + await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 7)); + SdkValueBoundary.ToClr(node.Value).ShouldBe(7); + + pending[0].SetResult(new NodeWriteOutcome(true, null)); // A confirmed late + await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 41)); + SdkValueBoundary.ToClr(node.Value).ShouldBe(41, "the device confirmed A after B's refusal: it holds A"); + node.StatusCode.ShouldBe(StatusCodes.Good); + node.Timestamp.ToDateTime().ShouldBeGreaterThan(pStamp); + + // A driver publication still wins afterwards (the late landing leaves no ownership behind). + _manager.WriteValue("v", 8, OpcUaStatus.Good, pStamp.AddMinutes(5), realm); + SdkValueBoundary.ToClr(node.Value).ShouldBe(8); + } + + /// #1041 guards: a late confirmation never overwrites anything NEWER than the revert — a driver publication + /// that landed after it, or a newer write that now owns the node (whose later refusal then reverts to A, the value the + /// device confirmed). + [Theory] + [InlineData("publication")] + [InlineData("newer-write")] + public async Task A_late_confirmation_never_overwrites_a_newer_tuple(string change) + { + var node = Node("Int32"); + _manager.WriteValue("v", 7, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw); + var pending = PendingOutcomes(); + + Write(node, 41).ShouldBe(ServiceResult.Good); // A + Write(node, 42).ShouldBe(ServiceResult.Good); // B + pending[1].SetResult(new NodeWriteOutcome(false, "B refused")); + await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 7)); + + if (change == "publication") _manager.WriteValue("v", 9, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw); + else Write(node, 43).ShouldBe(ServiceResult.Good); // C owns the node + var expected = change == "publication" ? 9 : 43; + + pending[0].SetResult(new NodeWriteOutcome(true, null)); // A confirmed late + await WaitUntilAsync(() => _outcomeLogger.Confirmed >= 1); + _outcomeLogger.Confirmed.ShouldBe(1, "positive control: A's confirmation was processed"); + SdkValueBoundary.ToClr(node.Value).ShouldBe(expected); + + if (change == "newer-write") + { + pending[2].SetResult(new NodeWriteOutcome(false, "C refused")); + await WaitUntilAsync(() => Equals(SdkValueBoundary.ToClr(node.Value), 41)); + SdkValueBoundary.ToClr(node.Value).ShouldBe(41, "C reverts to A — the last value the device confirmed"); + } + } + /// U-4 dual NodeId: the raw node and its UNS mirror both hold the fanned value P. Interleaved writes /// through BOTH NodeIds (A raw, B UNS, C UNS, D raw) are all refused in a mixed order; each NodeId reverts to the /// fanned P with P's status/timestamp, and the next fan-out publish lands on both (ownership released). diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorSourceRemovedTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorSourceRemovedTests.cs index 0b4d3afc6..f3c895582 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorSourceRemovedTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorSourceRemovedTests.cs @@ -259,6 +259,54 @@ public sealed class DriverHostActorSourceRemovedTests : RuntimeActorTestBase Replayed()[Path1].Value.ShouldBe(44.0); } + /// + /// Gitea #1041 (#979 follow-up): while an operator Restart rebuilds the driver object, a dependent still naming + /// its refs must not keep computing from the stopped object's last Good. It is told a non-Good status for the + /// restarted driver's ref (never for the untouched driver's), and the new object's first value — the + /// IDENTICAL value, so a (value, status) dedup cannot swallow the recovery — reaches it Good again. + /// + [Fact] + public void An_operator_restart_tells_dependents_the_ref_is_not_Good_until_the_new_driver_publishes() + { + ArrangeTwoDriversWithRetainedValues(); + + _host.Tell(new RestartDriver("c1", "DI-1", "tester", Guid.NewGuid())); + var gap = _holder.FishForMessage( + b => b.Items.Any(i => i.TagId == Path1 && !OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + gap.Items.ShouldNotContain(i => i.TagId == Path2, "DI-2 was not restarted"); + + AwaitAssert(() => _factory.Created.Count.ShouldBe(3), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + AwaitSubscribed("DI-1", Path1); + Driver("DI-1").FireDataChange(Path1, 11.0); + _holder.FishForMessage( + b => b.Items.Any(i => i.TagId == Path1 && Equals(i.Value, 11.0) && OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + } + + /// Gitea #1041: the config-change respawn (stop + spawn) leg of the same rule. + [Fact] + public void A_config_change_respawn_tells_dependents_the_ref_is_not_Good_until_the_new_driver_publishes() + { + ArrangeTwoDriversWithRetainedValues(); + + var revB = V3ArtifactSeeder.SeedV3Deployment(_db, RevB, + [.. BothDrivers, ("DI-1", "Modbus", "dev1", "temp", "Double", false)], NoRefs, enabled: true); + V3ArtifactSeeder.Dispatch(_host, _coordinator, revB, RevB); + var gap = _holder.FishForMessage( + b => b.Items.Any(i => i.TagId == Path1 && !OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + gap.Items.ShouldNotContain(i => i.TagId == Path2, "DI-2 was not respawned"); + + AwaitAssert(() => _factory.Created.Count.ShouldBe(3), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var respawned = Driver("DI-1"); + AwaitAssert(() => (respawned.LastSubscribedRefs ?? []).ShouldContain("Plant/Modbus/dev1/temp"), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + respawned.FireDataChange(Path1, 11.0); + _holder.FishForMessage( + b => b.Items.Any(i => i.TagId == Path1 && Equals(i.Value, 11.0) && OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + } + [Fact] public void A_supervision_restart_does_not_evict_the_drivers_retained_value() { From e967042fbb4997358f622beabd28f1470b8c013b Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:10:24 -0500 Subject: [PATCH 2/3] 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. --- .claude/rules/drivers.md | 3 +- docs/DriverLifecycle.md | 5 +- .../Drivers/DriverHostActor.cs | 29 ++++- .../OpcUa/OpcUaPublishActor.cs | 30 ++++-- ...ndencyMuxConsumerRegistrationGuardTests.cs | 102 ++++++++++++++++++ .../DeploymentArtifactApplyCostTests.cs | 24 +++++ .../DriverHostActorBootFromCacheTests.cs | 2 + .../DriverHostActorDegradedAckTests.cs | 3 + 8 files changed, 181 insertions(+), 17 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DependencyMuxConsumerRegistrationGuardTests.cs 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); From ca5ee2ac5749862feb8193e69ff12aa756139989 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:25:10 -0500 Subject: [PATCH 3/3] fix(virtualtags): #1061 a scheduler catch-up burst evaluates a timer tag once, not once per missed tick Root cause of the intermittent VirtualTagActorTimerTests coalesce failure (full suite only): Akka's HashedWheelTimer does not skip ticks it missed while its thread was stalled (GC pause, CPU starvation) - it delivers them all in one burst when it resumes. Measured with a parked scheduler thread: a 600 ms stall => 12 ticks within the same millisecond. Ticks that fell due during the gated run therefore landed just after the release, each a fresh evaluation, and broke the post-release bound. In production the same burst multiplied every timer tag's script runs by stall/interval after any stall. VirtualTagActor now drops a tick that lands within half an interval of the last timer evaluation (scheduler monotonic clock); the regular cadence is unaffected. New deterministic test parks the scheduler thread for 600 ms with the release inside the stall: failed 3/3 before the fix, passes after, with a cadence positive control. The in-flight assertion (Calls == 1 while gated) has no such mechanism - ticks during a run are dropped - and did not fail in 3 full-suite + 12 class-scoped trx runs under load average ~490. --- docs/VirtualTags.md | 2 +- .../VirtualTags/VirtualTagActor.cs | 22 ++++++++++- .../VirtualTags/VirtualTagActorTimerTests.cs | 37 +++++++++++++++++++ 3 files changed, 59 insertions(+), 2 deletions(-) diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 661528b3e..7c529f9cb 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -345,7 +345,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT - Pinned by `VirtualTagToVirtualTagFlowTests` (Host.Tests: real mux + host + Roslyn evaluator; value, change and disabled-upstream propagation), `VirtualTagOutputRoutingTests` (Runtime.Tests: mux pinning/replay/release, host routing, re-assert exclusion, runtime cycle backstop) and `DraftValidatorVirtualTagCycleTests`. - **Supervision restart re-applies.** A restart of `VirtualTagHostActor` builds a host with no children and no definitions; its `PostRestart` tells the parent `VirtualTagHostRestarted` and `DriverHostActor` re-sends the last `ApplyVirtualTags` (mirroring the scripted-alarm host's `ScriptedAlarmHostRestarted`), so VirtualTags resume without waiting for the next deploy. Pinned by `DriverHostActorVirtualTagTests.After_a_supervision_restart_the_virtual_tag_host_is_re_applied`. - **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`; there is no FK, so a concurrent bind is caught by the gate). As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`. -- **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`. +- **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. A tick that lands within half an interval of the last timer evaluation is dropped too (#1061): Akka's scheduler delivers every tick it missed during a stall of its thread (GC pause, CPU starvation) as one burst when it resumes, which used to run the script once per missed tick. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`. - **Calculation tags and scripted alarms still evaluate one script at a time per driver / per engine (deliberately, for now).** Neither blocks a thread — both await the run — but a slow script still delays its siblings. Running independent scripts in parallel was considered for #779 and not done, because it is not semantics-neutral: for Calculation, the single pump is what bounds a driver to one pool thread of script work (per-tag lanes would let N slow tags hold N pool threads, the pool Akka's dispatchers also run on, so it needs a bounded-parallelism knob), it would reorder publishes across tags, and the timer path would need per-tag exclusion with the pump; for scripted alarms, the engine gate is also the consistency boundary of the Part 9 state machine, persist-before-update and ack/shelve/load, a predicate's transition time is sampled just before its own run, and a store failure mid-batch today leaves later predicates un-run (in parallel they would already have run, moving their run-guard strike streaks and writing script logs for results that are then discarded). The out-of-process runner's batch-submit `IScriptRunner` (#750) is where that concurrency belongs, with the runner owning the bound. - **`IHistoryWriter`** — the equipment-namespace path threads `Historize` end-to-end and `VirtualTagHostActor` invokes the injected writer on historized results (H5); the writer is resolved through `DriverHostActor` DI with a `NullHistoryWriter` default. No *durable* writer ships on this seam — durable continuous historization now flows through the separate `ContinuousHistorizationRecorder` → HistorianGateway `WriteLiveValues` path (see the `IHistoryWriter` section above and [Historian.md](Historian.md)). diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagActor.cs index 5c67825cc..c72bc4fb0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagActor.cs @@ -130,6 +130,8 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash private readonly bool _changeTriggered; private readonly int? _timerIntervalMs; private ICancelable? _timer; + // Gitea #1061: scheduler-clock time of the last tick that evaluated (null until the first). + private TimeSpan? _lastTimerEvaluation; // One outstanding RunnerRecovered wait at most: a burst of Unavailable results re-evaluates once (latest-wins). private bool _recoveryArmed; // R02:P6 — a script failing on every trigger of a 1 Hz input published one cluster-wide DPS @@ -248,7 +250,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash Receive(wake => wake.Consume(items => OnDependencyBatch(new(items)))); Receive(_ => OnReassertValue()); Receive(_ => RetrySource()); - Receive(_ => Evaluate(DateTime.UtcNow)); + Receive(_ => OnTimerTick()); Receive(_ => { _recoveryArmed = false; @@ -294,6 +296,24 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash _mux?.Tell(new DependencyMuxActor.UnregisterInterest(Self)); } + /// + /// A timer tick (lmxopcua#783). Gitea #1061: Akka's scheduler does not skip the ticks it missed while its thread + /// was stalled (a GC pause, CPU starvation) — it delivers every one of them in a single burst when it resumes (a + /// 600 ms stall ⇒ 12 ticks inside one millisecond). Each used to be a full evaluation, so one stall multiplied + /// every timer tag's script runs by the stall length over its interval. A tick that lands within half an interval + /// of the last timer evaluation is such a catch-up duplicate and is dropped; the regular cadence (one tick per + /// interval, the wheel's jitter a fraction of the 50 ms floor) is never affected. Ticks during a run are still + /// dropped by . + /// + private void OnTimerTick() + { + var now = Context.System.Scheduler.MonotonicClock; + if (_lastTimerEvaluation is { } last && _timerIntervalMs is { } ms && now - last < TimeSpan.FromMilliseconds(ms / 2.0)) + return; + _lastTimerEvaluation = now; + Evaluate(DateTime.UtcNow); + } + private void ScheduleSourceRetry() { _sourceBindingRetry?.Cancel(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagActorTimerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagActorTimerTests.cs index eed5469c9..d2da4cb91 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagActorTimerTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagActorTimerTests.cs @@ -72,6 +72,43 @@ public sealed class VirtualTagActorTimerTests : RuntimeActorTestBase $"coalesced: only real ticks may land after the release ({sinceRelease.ElapsedMilliseconds} ms since release)"); } + /// + /// Gitea #1061 — the real cause of the intermittent full-suite failure above. Akka's scheduler does not skip the + /// ticks it missed while its thread was stalled (a GC pause, CPU starvation under a loaded run): it delivers them + /// all in ONE burst when it resumes (measured: a 600 ms stall ⇒ 12 ticks within the same millisecond). Ticks that + /// fell due during a gated run therefore reached the actor just after the run, each one a fresh evaluation. The + /// stall is produced deterministically here by parking the scheduler's own thread, with the release inside it. + /// A catch-up burst must collapse to one evaluation; the cadence afterwards is unaffected (positive control). + /// + [Fact] + public void A_scheduler_catch_up_burst_after_a_slow_run_evaluates_once_not_once_per_missed_tick() + { + var parent = CreateTestProbe(); + var evaluator = new CountingEvaluator(gateFirst: true); + parent.ChildActorOf(VirtualTagActor.Props("vt-1", "expr", evaluator: evaluator, timerIntervalMs: 50), TestContext.Current.CancellationToken); + AwaitCondition(() => evaluator.Calls == 1, PresenceBudget, TestContext.Current.CancellationToken); + + // Park the scheduler's thread for 600 ms (~12 intervals) and finish the slow run inside that stall. + using var stalled = new ManualResetEventSlim(); + using var resumed = new ManualResetEventSlim(); + Sys.Scheduler.Advanced.ScheduleOnce(TimeSpan.Zero, () => { stalled.Set(); Thread.Sleep(600); resumed.Set(); }); + stalled.Wait(TestContext.Current.CancellationToken); + evaluator.Release(); + parent.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + resumed.Wait(TestContext.Current.CancellationToken); + var sinceResume = System.Diagnostics.Stopwatch.StartNew(); + + // The burst lands now. Coalesced: one catch-up evaluation plus whatever real ticks elapsed meanwhile. + Thread.Sleep(100); + var elapsedTicks = (int)(sinceResume.ElapsedMilliseconds / 50) + 1; + evaluator.Calls.ShouldBeLessThanOrEqualTo(1 + 1 + elapsedTicks, + $"a catch-up burst ran once per missed tick ({sinceResume.ElapsedMilliseconds} ms since the scheduler resumed)"); + + // Positive control: the timer still evaluates on its cadence afterwards. + var before = evaluator.Calls; + AwaitCondition(() => evaluator.Calls >= before + 2, PresenceBudget, TestContext.Current.CancellationToken); + } + [Fact] public void The_timer_stops_when_the_actor_stops() {