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:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user