Merge runtime follow-ups: timer VT drops scheduler catch-up tick bursts after a stall (#1061, real cause of the coalesce flake), late device confirmation after revert lands (#1041), artifact hash off the pinned thread + mux ConsumerRefs guard (#1054)
This commit is contained in:
@@ -295,7 +295,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -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)).
|
||||
|
||||
|
||||
@@ -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<long, NodeTuple> _revertedAttempts = new();
|
||||
private long _revertedRevision = -1;
|
||||
|
||||
internal readonly record struct WriteStamp(EquipmentVariableState Owner, long Token);
|
||||
|
||||
/// <summary>One (value, status, source timestamp) tuple of the node.</summary>
|
||||
@@ -43,6 +51,10 @@ internal sealed class EquipmentVariableState(NodeState? parent, object ownerLock
|
||||
Revert,
|
||||
/// <summary>A failure superseded by a newer attempt or a driver publication.</summary>
|
||||
Superseded,
|
||||
/// <summary>#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
|
||||
/// (<see cref="ApplyLateConfirmation"/>).</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1041: closes the window after the owning attempt <paramref name="failedToken"/> was refused and the node reverted
|
||||
/// (caller holds <c>ownerLock</c> 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 <see cref="ResolveWriteOutcome"/>), together with such attempts left over from earlier
|
||||
/// reverts.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>#1041: lands a <see cref="WriteOutcomeAction.LateConfirm"/> tuple on the node (caller holds
|
||||
/// <c>ownerLock</c> and notifies subscribers). A still-pending NEWER reverted attempt can follow it the same way.</summary>
|
||||
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;
|
||||
|
||||
@@ -4076,6 +4076,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);
|
||||
@@ -4099,7 +4109,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;
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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<DependencyMuxActor.ProjectedDependencyWake>(wake => wake.Consume(items => OnDependencyBatch(new(items))));
|
||||
Receive<ReassertValue>(_ => OnReassertValue());
|
||||
Receive<RetrySourceBinding>(_ => RetrySource());
|
||||
Receive<TimerTick>(_ => Evaluate(DateTime.UtcNow));
|
||||
Receive<TimerTick>(_ => OnTimerTick());
|
||||
Receive<RunnerRecovered>(_ =>
|
||||
{
|
||||
_recoveryArmed = false;
|
||||
@@ -294,6 +296,24 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
_mux?.Tell(new DependencyMuxActor.UnregisterInterest(Self));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Evaluating"/>.
|
||||
/// </summary>
|
||||
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();
|
||||
|
||||
@@ -373,6 +373,73 @@ public sealed class Sdk2EquipmentVariableTests : IAsyncLifetime
|
||||
node.StatusCode.ShouldBe(StatusCodes.Good);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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".
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>#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).</summary>
|
||||
[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");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>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).</summary>
|
||||
|
||||
+102
@@ -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}");
|
||||
}
|
||||
+24
@@ -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) { }
|
||||
|
||||
+2
@@ -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]
|
||||
|
||||
+3
@@ -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);
|
||||
|
||||
|
||||
+48
@@ -259,6 +259,54 @@ public sealed class DriverHostActorSourceRemovedTests : RuntimeActorTestBase
|
||||
Replayed()[Path1].Value.ShouldBe(44.0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<VirtualTagActor.DependencyValueBatch>(
|
||||
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<VirtualTagActor.DependencyValueBatch>(
|
||||
b => b.Items.Any(i => i.TagId == Path1 && Equals(i.Value, 11.0) && OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget,
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Gitea #1041: the config-change respawn (stop + spawn) leg of the same rule.</summary>
|
||||
[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<VirtualTagActor.DependencyValueBatch>(
|
||||
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<VirtualTagActor.DependencyValueBatch>(
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -72,6 +72,43 @@ public sealed class VirtualTagActorTimerTests : RuntimeActorTestBase
|
||||
$"coalesced: only real ticks may land after the release ({sinceRelease.ElapsedMilliseconds} ms since release)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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<VirtualTagActor.EvaluationResult>(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()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user