docs: fill missing XML docs and strip tracking IDs from src comments

Clears CommentChecker findings in src/ (3,280 -> 209, the remainder being false
positives like PLC-5/IEEE-754/M0.0) by adding missing summaries/params/returns,
normalising inheritdoc usage, and removing Gitea/review tracking IDs while keeping
the rationale they annotated. Comment-only: comment-stripped sources are identical
to the parent commit.
This commit is contained in:
Joseph Doherty
2026-10-15 06:14:58 -04:00
parent ebcbd81fca
commit 826312befe
430 changed files with 4434 additions and 3923 deletions
@@ -12,7 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Communication;
/// <summary>
/// Posts this node's <see cref="ApplyAck"/> to central's <c>CentralCommandService</c> as a unary
/// gRPC call (mesh gRPC command plane, Task 1B.2), the <c>MeshTransport:Mode = Grpc</c>
/// gRPC call (mesh gRPC command plane), the <c>MeshTransport:Mode = Grpc</c>
/// cross-mesh ack transport.
/// </summary>
/// <remarks>
@@ -233,7 +233,7 @@ public sealed class GrpcApplyAckSender : IApplyAckSender, IDisposable
return new CentralCommandService.CentralCommandServiceClient(channel);
}
/// <inheritdoc />
/// <summary>Disposes every cached gRPC channel.</summary>
public void Dispose()
{
foreach (var channel in _channels.Values)
@@ -27,7 +27,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache;
/// <para>
/// <b>Why <see langword="null"/>, not throw.</b> The caller treats <see langword="null"/>
/// identically to today's "reconcile returned null": an apply failure that keeps
/// last-known-good and does not advance the revision. A typed "no bytes" keeps the #485
/// last-known-good and does not advance the revision. A typed "no bytes" keeps the
/// contract explicit and cannot escape as an unhandled actor message.
/// </para>
/// </remarks>
@@ -143,7 +143,7 @@ public sealed class GrpcDeploymentArtifactFetcher : IDeploymentArtifactFetcher,
return new DeploymentArtifactService.DeploymentArtifactServiceClient(channel);
}
/// <inheritdoc />
/// <summary>Disposes every cached gRPC channel.</summary>
public void Dispose()
{
foreach (var channel in _channels.Values)
@@ -24,6 +24,12 @@ public interface IDeploymentArtifactCache
/// without limit.
/// </para>
/// </remarks>
/// <param name="clusterId">The cluster the artifact belongs to.</param>
/// <param name="deploymentId">The deployment identifier.</param>
/// <param name="revisionHash">The revision hash used for the integrity check.</param>
/// <param name="artifact">The artifact bytes.</param>
/// <param name="ct">Cancels the store.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task StoreAsync(string clusterId, string deploymentId, string revisionHash,
byte[] artifact, CancellationToken ct = default);
@@ -38,6 +44,9 @@ public interface IDeploymentArtifactCache
/// missing half looks like a deliberate configuration rather than an error.
/// </para>
/// </remarks>
/// <param name="clusterId">The cluster to read.</param>
/// <param name="ct">Cancels the read.</param>
/// <returns>The current artifact, or <see langword="null"/> on a miss or failed integrity check.</returns>
Task<CachedDeploymentArtifact?> GetCurrentAsync(string clusterId, CancellationToken ct = default);
/// <summary>
@@ -57,6 +66,8 @@ public interface IDeploymentArtifactCache
/// be quiet.
/// </para>
/// </remarks>
/// <param name="ct">Cancels the read.</param>
/// <returns>The current artifact, or <see langword="null"/> when none is cached.</returns>
Task<CachedDeploymentArtifact?> GetCurrentUnkeyedAsync(CancellationToken ct = default);
}
@@ -22,7 +22,7 @@ public interface IDeploymentArtifactFetcher
/// The verified artifact bytes, or <see langword="null"/> on ANY failure — every configured
/// endpoint unreachable/NotFound, a zero-length stream, or a SHA-256 mismatch. A
/// <see langword="null"/> is "no answer," NEVER an empty configuration: the caller treats it as
/// an apply failure and keeps last-known-good (the #485 contract).
/// an apply failure and keeps last-known-good (the unreadable-artifact contract).
/// </returns>
Task<byte[]?> FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken ct);
}
@@ -41,6 +41,9 @@ public sealed class LocalDbDeploymentArtifactCache : IDeploymentArtifactCache
private readonly ILocalDb _db;
private readonly ILogger<LocalDbDeploymentArtifactCache> _logger;
/// <summary>Initializes the cache over the pair-local database.</summary>
/// <param name="db">The pair-local database.</param>
/// <param name="logger">The logger.</param>
public LocalDbDeploymentArtifactCache(ILocalDb db, ILogger<LocalDbDeploymentArtifactCache> logger)
{
ArgumentNullException.ThrowIfNull(db);
@@ -41,7 +41,7 @@ public enum ClusterFilterMode
}
/// <summary>
/// The data-plane authorization inputs decoded out of a deployment artifact for one node (#520).
/// The data-plane authorization inputs decoded out of a deployment artifact for one node.
/// </summary>
/// <param name="ClusterId">The node's cluster per its <c>ClusterNode</c> row, or null on a
/// single-cluster / legacy artifact where no scoping applies.</param>
@@ -149,7 +149,7 @@ public static class DeploymentArtifact
/// Every failure — corrupt stream, truncated stream, over-limit inflation — is reported as
/// <see cref="JsonException"/> so it lands in the exact catch the malformed-JSON path already
/// owns: the static wrappers degrade to empty results, and the apply paths fail the apply and
/// keep last-known-good (#485 "no bytes is no answer"). Unusable bytes are unusable bytes; the
/// keep last-known-good ("no bytes is no answer"). Unusable bytes are unusable bytes; the
/// reason they are unusable does not change any caller's decision.
/// </para>
/// </remarks>
@@ -269,7 +269,7 @@ public static class DeploymentArtifact
/// <summary>
/// Parse the data-plane authorization inputs a node needs to authenticate OPC UA sessions:
/// the <c>ApiKeys</c> the artifact carries and the <c>NodeAcls</c> granting their principals
/// permissions (#520, stage 4). See <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/>
/// permissions. See <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/>
/// for the scoping + leniency contract.
/// </summary>
/// <param name="blob">The deployment artifact blob to parse.</param>
@@ -859,7 +859,7 @@ internal sealed class ParsedDeploymentArtifact : IDisposable
/// <summary>
/// The data-plane authorization inputs a node needs to authenticate OPC UA sessions:
/// the <c>ApiKeys</c> the artifact carries and the <c>NodeAcls</c> granting their principals
/// permissions (#520, stage 4).
/// permissions.
/// </summary>
/// <remarks>
/// <para>
@@ -876,7 +876,7 @@ internal sealed class ParsedDeploymentArtifact : IDisposable
/// <para>
/// Lenient like every other parser here: an artifact carrying neither section yields empty
/// lists. The caller must NOT treat that as "no keys are valid" and install it — see issue
/// #485; the apply paths only reach this with bytes that already passed their own guard.
/// the apply paths only reach this with bytes that already passed their own guard.
/// </para>
/// </remarks>
/// <param name="nodeId">The node's identity, used to resolve cluster scope for the grants.</param>
@@ -85,7 +85,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
public static readonly TimeSpan DefaultApplyWedgeTimeout = TimeSpan.FromMinutes(5);
/// <summary>
/// Gitea #601 — how long an Applied ack waits for <c>OpcUaPublishActor</c>'s address-space apply
/// How long an Applied ack waits for <c>OpcUaPublishActor</c>'s address-space apply
/// outcome (<see cref="OpcUa.OpcUaPublishActor.RebuildCompleted"/>) before it is sent anyway.
/// </summary>
/// <remarks>
@@ -99,7 +99,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </remarks>
public static readonly TimeSpan DefaultApplyOutcomeTimeout = DeployTimings.ApplyOutcomeTimeout;
/// <summary>Gitea #601 — the reason prefix of a degraded ack sent because the outcome TIMED OUT, so an
/// <summary>The reason prefix of a degraded ack sent because the outcome TIMED OUT, so an
/// operator can tell "not reported in time" from a real sink failure.</summary>
public const string OutcomeNotReportedReasonPrefix = "address-space apply outcome not reported in time";
@@ -174,7 +174,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <see langword="null"/> when none was wired (per-cluster mesh Phase 4). On a driver-role node
/// this is the replicated LocalDb store (<c>LocalDbAlarmConditionStateStore</c>) so condition
/// state survives without central SQL; when null the actor skips spawning the alarm host (the
/// ConfigDb-backed EF fallback was retired in Phase 4 Task 9).
/// ConfigDb-backed EF fallback was retired).
/// </summary>
private readonly IAlarmStateStore? _alarmStateStore;
@@ -265,7 +265,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private RevisionHash? _currentRevision;
/// <summary>
/// Gitea #601 — the last address-space apply of <see cref="_currentRevision"/> reported DEGRADED (or no
/// The last address-space apply of <see cref="_currentRevision"/> reported DEGRADED (or no
/// outcome in time). A re-dispatch of that same revision then RE-APPLIES instead of taking the
/// idempotent "already at this revision" short-circuit: the short-circuit would ack a clean Applied
/// for an address space known to be partial, and the re-apply is what repairs it (a degraded
@@ -274,7 +274,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </summary>
private bool _currentRevisionDegraded;
/// <summary>Gitea #601 — Applied acks held until the address-space apply reports its outcome, keyed by
/// <summary>Applied acks held until the address-space apply reports its outcome, keyed by
/// the apply's correlation id (echoed back in <see cref="OpcUa.OpcUaPublishActor.RebuildCompleted"/>).</summary>
private readonly Dictionary<CorrelationId, PendingAck> _pendingAcks = new();
@@ -330,8 +330,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private readonly Dictionary<(AddressSpaceRealm Realm, string NodeId), (string DriverInstanceId, string RawPath)> _driverRefByNodeId = new();
/// <summary>(DriverInstanceId, RawPath = alarm ConditionId) → materialised condition NodeId(s) (realm-tagged).
/// v3 Batch 4: a native alarm is a single condition at the RawPath (Raw realm); WP4 adds the referencing
/// equipment notifier NodeIds. Resolves a native alarm transition to the materialised Part 9 condition
/// v3 Batch 4: a native alarm is a single condition at the RawPath (Raw realm); the referencing
/// equipment notifier NodeIds are added on top. Resolves a native alarm transition to the materialised Part 9 condition
/// node(s). Alarm tags are conditions, not value variables, so they are kept OUT of the value maps +
/// value-subscription set.</summary>
private readonly Dictionary<(string DriverInstanceId, string RawPath), HashSet<NodeRealmRef>> _alarmNodeIdByDriverRef = new();
@@ -408,7 +408,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// first apply — a child spawned before any apply is handed nothing, which is what it should have.
/// <para>It is only ever rebuilt by a SUCCESSFUL apply, so after a failed one it deliberately lingers on
/// the last-good composition — matching the address space, drivers and subscriptions that also keep
/// serving through a failed apply (#485/#486). A respawn or reprovision in that window therefore hands
/// serving through a failed apply. A respawn or reprovision in that window therefore hands
/// the child the last-known-good set, not an empty one.</para></summary>
private readonly Dictionary<string, DesiredSubscriptionSet> _desiredByDriver = new(StringComparer.Ordinal);
@@ -434,7 +434,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <summary>
/// Where the Primary <b>data-plane</b> verdict is published for drivers that must know it
/// directly (Gitea #511). Null on nodes that wire no redundancy manager.
/// directly. Null on nodes that wire no redundancy manager.
/// </summary>
/// <remarks>
/// Note the different verdict from <see cref="_redundancyRoleView"/>: that one carries
@@ -446,16 +446,16 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private readonly IDriverPrimaryRoleSource? _primaryRoleSource;
/// <summary>
/// Gitea #537: where the continuous-historization <b>capture</b> verdict is published for the
/// Where the continuous-historization <b>capture</b> verdict is published for the
/// recorder, which taps the mux fan-out and so needs the decision off its own mailbox. Null on
/// nodes that wire no redundancy manager.
/// </summary>
private readonly IHistorizationRoleView? _historizationRoleView;
/// <summary>Gitea #674 review: where the HistoryUpdate verdict is published. Null on nodes that wire no redundancy manager.</summary>
/// <summary>Where the HistoryUpdate verdict is published. Null on nodes that wire no redundancy manager.</summary>
private readonly IHistoryUpdateRoleView? _historyUpdateRoleView;
/// <summary>Gitea #674 review: whether any redundancy snapshot has reached this host — the HistoryUpdate gate stays
/// <summary>Whether any redundancy snapshot has reached this host — the HistoryUpdate gate stays
/// closed until one has (see <see cref="PrimaryGatePolicy.ShouldServeHistoryUpdate"/>).</summary>
private bool _redundancySnapshotReceived;
@@ -468,20 +468,20 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </summary>
private readonly Func<CommonsNodeId, bool>? _sharesHistorizationScopeWithLocal;
/// <summary>Gitea #672: whether an UNREACHABLE recording Primary still stands this node's historization
/// <summary>Whether an UNREACHABLE recording Primary still stands this node's historization
/// capture down (<c>false</c>) or not (<c>true</c>, the default). See <see cref="ComputeHistorizationVerdict"/>.</summary>
private readonly bool _captureWhilePrimaryUnreachable;
/// <summary>Gitea #672: the last redundancy snapshot's nodes, so a reachability change can re-derive the
/// <summary>The last redundancy snapshot's nodes, so a reachability change can re-derive the
/// historization capture verdict without waiting for the next snapshot — which, when the recording Primary
/// crashed, may not come until auto-down (the redundancy singleton usually lived on that Primary).</summary>
private IReadOnlyList<NodeRedundancyState>? _lastRedundancySnapshotNodes;
/// <summary>Gitea #672: peers the cluster failure detector currently reports unreachable (never this node).
/// <summary>Peers the cluster failure detector currently reports unreachable (never this node).
/// Fed by <see cref="Akka.Cluster.ClusterEvent.ReachabilityEvent"/>; cleared for an address that comes Up again.</summary>
private readonly HashSet<CommonsNodeId> _unreachableNodes = new();
/// <summary>Gitea #672: the unreachable recording Primary this node is currently capturing in place of, or
/// <summary>The unreachable recording Primary this node is currently capturing in place of, or
/// null — drives the once-per-transition Information log.</summary>
private CommonsNodeId? _capturingForUnreachablePrimary;
@@ -489,10 +489,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// path republishes only a CHANGED verdict.</summary>
private bool? _lastPublishedHistorizationVerdict;
/// <summary>Whether this actor holds its own (#672) cluster reachability subscription.</summary>
/// <summary>Whether this actor holds its own cluster reachability subscription.</summary>
private bool _subscribedToReachabilityEvents;
/// <summary>Gitea #601 — how long an Applied ack waits for the address-space outcome (see
/// <summary>How long an Applied ack waits for the address-space outcome (see
/// <see cref="DefaultApplyOutcomeTimeout"/>).</summary>
private readonly TimeSpan _applyOutcomeTimeout;
@@ -511,7 +511,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// re-publishes, and read once by <see cref="CommsRecoveryAudit"/> after the driver reconnects.
/// <para><b>It is a tripwire, not a mechanism.</b> Nothing depends on it being correct for the data
/// plane to behave: the host publishes nothing Good on reconnect either way. What it buys is that a
/// driver which reconnects and then fails to re-publish — the pre-STAB-18 MQTT shape, and what any
/// driver which reconnects and then fails to re-publish — the MQTT shape, and what any
/// future push driver without an initial push will do — produces a Warning and a metered count
/// instead of a subscription that silently reports Bad forever.</para>
/// <para>Keyed by RawPath, so a raw node and its UNS mirrors count once: the operator is being told
@@ -538,7 +538,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private readonly string? _replicationPeerHost;
/// <summary>
/// Review R6 MINOR-4: identifies the alarm-queue-sharing peer when <see cref="_replicationPeerHost"/> is
/// Identifies the alarm-queue-sharing peer when <see cref="_replicationPeerHost"/> is
/// unknown — the passive (listening) half of a pair, which replicates the same rows but dials nobody. Before
/// this the passive half had no peer to defer to, so as Secondary it kept draining alongside its Primary
/// partner and every alarm event reached the historian twice. Null ⇒ no peer known ⇒ never stand down.
@@ -636,8 +636,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// VirtualTag host instead of spawning a real <see cref="VirtualTagHostActor"/> child, so tests
/// can intercept the <see cref="VirtualTagHostActor.ApplyVirtualTags"/> message. Null in
/// production (the real host is spawned).</param>
/// <param name="loggerFactory">Retained for constructor-signature stability; unused since Phase 4
/// Task 9 retired the <c>EfAlarmConditionStateStore</c> fallback that consumed it. Defaults to null.</param>
/// <param name="loggerFactory">Retained for constructor-signature stability; unused since the
/// <c>EfAlarmConditionStateStore</c> fallback that consumed it was retired. Defaults to null.</param>
/// <param name="scriptRootLogger">Optional root script logger required to spawn the ScriptedAlarm
/// host (the engine + its script logging hang off it). When null the ScriptedAlarm host is left
/// unspawned — the graceful dev/None-deployment path.</param>
@@ -648,21 +648,47 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <param name="invokerFactory">Optional Phase 6.1 resilience-invoker factory used to attach an
/// <see cref="IDriverCapabilityInvoker"/> to each spawned driver; defaults to
/// <see cref="NullDriverCapabilityInvokerFactory"/> (pass-through) when not supplied.</param>
/// <param name="driverMemberCountProvider">Test seam: overrides the count of Up <c>driver</c>-role cluster
/// members the Primary gate reads while the role is unknown. When null the cluster state is read.</param>
/// <param name="deploymentArtifactCache">Optional node-local cache of applied deployment artifacts, so the node
/// can boot from its last-known-good configuration while central SQL is unreachable. Null skips caching.</param>
/// <param name="redundancyRoleView">Where the node's redundancy role is published and read. Null on nodes
/// that wire no redundancy manager.</param>
/// <param name="replicationPeerHost">Host of the LocalDb replication peer this node dials, used to identify the
/// partner that shares its alarm queue. Null when the node dials nobody.</param>
/// <param name="fetchAndCacheMode">When <c>true</c>, the node never reads central SQL for configuration and instead
/// fetches artifacts through <paramref name="artifactFetcher"/> and boots from its local cache.</param>
/// <param name="artifactFetcher">Fetches deployment artifacts from central over gRPC in
/// <paramref name="fetchAndCacheMode"/>. Null when that mode is off.</param>
/// <param name="alarmStateStore">Per-cluster mesh Phase 4: scripted-alarm condition-state store. On a
/// driver-role node this is the replicated LocalDb store, so condition state persists with no
/// ConfigDb; null skips spawning the alarm host (the ConfigDb-backed EF fallback was retired in
/// Phase 4 Task 9). Defaults to null.</param>
/// <param name="telemetryHub">Per-cluster mesh Phase 5: optional node-local live-telemetry hub each
/// ConfigDb; null skips spawning the alarm host (the ConfigDb-backed EF fallback was retired).
/// Defaults to null.</param>
/// <param name="telemetryHub">Optional node-local live-telemetry hub each
/// Primary-gated native-alarm transition is also emitted into, and which is threaded into the spawned
/// VirtualTag + ScriptedAlarm hosts. Defaults to null (admin-only nodes / tests skip the emit).</param>
/// <param name="primaryRoleSource">Where the Primary data-plane verdict is published, for drivers that assert a
/// standing exclusive identity on a shared external system. Null on nodes that wire no redundancy manager.</param>
/// <param name="historizationRoleView">Where the continuous-historization capture verdict is published. Null on
/// nodes that wire no redundancy manager.</param>
/// <param name="sharesHistorizationScopeWithLocal">Tests whether a node named in a redundancy snapshot serves this
/// node's address space and therefore records the same historized refs. Null means this node never stands down.</param>
/// <param name="applyWedgeTimeout">How long the host may sit in <see cref="Applying"/> before the
/// wedge watchdog logs a Warning. Defaults to <see cref="DefaultApplyWedgeTimeout"/>.</param>
/// <param name="reprovisionBackoff">Backoff before a failed driver re-provision is retried. Null uses the default.</param>
/// <param name="commsRecoveryAuditDelay">Archreview 03/S15: how long after a driver reconnects the
/// recovery audit waits before reporting refs still latched <c>BadNoCommunication</c>. Defaults to
/// <see cref="DefaultCommsRecoveryAuditDelay"/>; tests shorten it.</param>
/// <param name="applyOutcomeTimeout">Gitea #601: how long an Applied ack waits for the address-space
/// <param name="sharesAlarmQueueWithLocal">Tests whether a node named in a redundancy snapshot holds this node's
/// replicated alarm queue, for a node that knows no <paramref name="replicationPeerHost"/>. Null means no such
/// peer is known.</param>
/// <param name="applyOutcomeTimeout">How long an Applied ack waits for the address-space
/// apply outcome before it is sent anyway, marked degraded ("outcome unknown"). Defaults to
/// <see cref="DefaultApplyOutcomeTimeout"/>; tests shorten it.</param>
/// <param name="captureWhilePrimaryUnreachable">When <c>true</c> (default), a node stops deferring historization
/// capture to a mesh-partner Primary the cluster failure detector reports unreachable.</param>
/// <param name="historyUpdateRoleView">Where the OPC UA HistoryUpdate verdict is published for the node manager's
/// HistoryUpdate Primary gate. Null on nodes that wire no redundancy manager.</param>
/// <returns>The Akka.NET <see cref="Akka.Actor.Props"/> used to spawn this actor.</returns>
public static Props Props(
IDbContextFactory<OtOpcUaConfigDbContext>? dbFactory,
@@ -729,8 +755,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// for historized VirtualTag results; defaults to <see cref="NullHistoryWriter"/>.</param>
/// <param name="virtualTagHostOverride">Test seam: when supplied, used as the VirtualTag host
/// instead of spawning a real <see cref="VirtualTagHostActor"/> child.</param>
/// <param name="loggerFactory">Retained for constructor-signature stability; unused since Phase 4
/// Task 9 retired the <c>EfAlarmConditionStateStore</c> fallback that consumed it. Defaults to null.</param>
/// <param name="loggerFactory">Retained for constructor-signature stability; unused since the
/// <c>EfAlarmConditionStateStore</c> fallback that consumed it was retired. Defaults to null.</param>
/// <param name="scriptRootLogger">Optional root script logger required to spawn the ScriptedAlarm
/// host; when null the host is left unspawned.</param>
/// <param name="scriptedAlarmHostOverride">Test seam: when supplied, used as the ScriptedAlarm host
@@ -745,19 +771,27 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// When supplied, each successful apply stores its artifact so the node can boot from its
/// last-known-good configuration while central SQL is unreachable. Null on admin-only nodes and in
/// tests that do not exercise the cache — caching is then simply skipped.</param>
/// <param name="redundancyRoleView">Where the node's redundancy role is published and read. Null on nodes
/// that wire no redundancy manager.</param>
/// <param name="replicationPeerHost">Host of the LocalDb replication peer this node dials, used to identify the
/// partner that shares its alarm queue. Null when the node dials nobody.</param>
/// <param name="fetchAndCacheMode">When <c>true</c>, the node never reads central SQL for configuration and instead
/// fetches artifacts through <paramref name="artifactFetcher"/> and boots from its local cache.</param>
/// <param name="artifactFetcher">Fetches deployment artifacts from central over gRPC in
/// <paramref name="fetchAndCacheMode"/>. Null when that mode is off.</param>
/// <param name="alarmStateStore">Per-cluster mesh Phase 4: scripted-alarm condition-state store. On a
/// driver-role node this is the replicated LocalDb store; null skips spawning the alarm host (the
/// ConfigDb-backed EF fallback was retired in Phase 4 Task 9).</param>
/// <param name="telemetryHub">Per-cluster mesh Phase 5: optional node-local live-telemetry hub each
/// ConfigDb-backed EF fallback was retired).</param>
/// <param name="telemetryHub">Optional node-local live-telemetry hub each
/// Primary-gated native-alarm transition is also emitted into, and which is threaded into the spawned
/// VirtualTag + ScriptedAlarm hosts. Null (admin-only nodes / tests) skips the emit and passes null down.</param>
/// <param name="primaryRoleSource">Gitea #511: where the Primary <i>data-plane</i> verdict is published
/// <param name="primaryRoleSource">Where the Primary <i>data-plane</i> verdict is published
/// for drivers that assert a standing exclusive identity on a shared external system — today the MQTT
/// driver's Sparkplug primary-host STATE claim. Deliberately a separate parameter from
/// <paramref name="redundancyRoleView"/> even though the production object implements both: a test that
/// supplies only a role-view double must not silently also satisfy this, or its primary-role assertions
/// pass without the publish ever happening. Null on nodes that wire no redundancy manager.</param>
/// <param name="historizationRoleView">Gitea #537: where the continuous-historization <i>capture</i>
/// <param name="historizationRoleView">Where the continuous-historization <i>capture</i>
/// verdict is published, for the recorder that taps the mux fan-out. A third distinct parameter for
/// the same reason <paramref name="primaryRoleSource"/> is a second — the production object
/// implements all three, and a test double supplied for one must not silently satisfy the others.
@@ -769,21 +803,25 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <param name="applyWedgeTimeout">How long the host may sit in <see cref="Applying"/> before the
/// wedge watchdog logs a Warning. Defaults to <see cref="DefaultApplyWedgeTimeout"/>; a test shortens
/// it so the watchdog is observable in a test's lifetime.</param>
/// <param name="reprovisionBackoff">Backoff before a failed driver re-provision is retried. Null uses the default.</param>
/// <param name="commsRecoveryAuditDelay">Archreview 03/S15: how long after a driver reconnects the
/// recovery audit waits before reporting refs still latched <c>BadNoCommunication</c>. Defaults to
/// <see cref="DefaultCommsRecoveryAuditDelay"/>; a test shortens it for the same reason.</param>
/// <param name="sharesAlarmQueueWithLocal">Review R6 MINOR-4: tests whether a node named in a redundancy
/// <param name="sharesAlarmQueueWithLocal">Tests whether a node named in a redundancy
/// snapshot holds this node's replicated alarm queue, for a node that knows no
/// <paramref name="replicationPeerHost"/> — the PASSIVE half of a LocalDb pair (ApiKey + SyncListenPort, no
/// PeerAddress), whose partner is its per-cluster mesh partner. Ignored when
/// <paramref name="replicationPeerHost"/> is set. Null ⇒ no such peer is known and this node never stands its
/// drain down.</param>
/// <param name="captureWhilePrimaryUnreachable">Gitea #672 (<c>ContinuousHistorization:CaptureWhilePrimaryUnreachable</c>,
/// <param name="applyOutcomeTimeout">How long an Applied ack waits for the address-space apply outcome before it is
/// sent anyway, marked degraded ("outcome unknown"). Defaults to <see cref="DefaultApplyOutcomeTimeout"/>; tests
/// shorten it.</param>
/// <param name="captureWhilePrimaryUnreachable">(<c>ContinuousHistorization:CaptureWhilePrimaryUnreachable</c>,
/// default <c>true</c>): when a mesh-partner Primary this node would stand its historization capture down for is
/// reported UNREACHABLE by the cluster failure detector, stop deferring to it and capture — rather than waiting
/// for auto-down + a fresh redundancy snapshot. Affects ONLY the historization capture verdict; the alarm drain
/// and the Primary data-plane verdict are unchanged. <c>false</c> restores the pre-#672 behaviour.</param>
/// <param name="historyUpdateRoleView">Gitea #674 review: where the OPC UA HistoryUpdate verdict
/// and the Primary data-plane verdict are unchanged. <c>false</c> restores the earlier behaviour.</param>
/// <param name="historyUpdateRoleView">Where the OPC UA HistoryUpdate verdict
/// (<see cref="PrimaryGatePolicy.ShouldServeHistoryUpdate"/> — the data-plane verdict, but closed until the first
/// redundancy snapshot) is published for the node manager's HistoryUpdate Primary gate. Null on nodes that wire no
/// redundancy manager.</param>
@@ -898,12 +936,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
/// <summary>
/// Review R1 m2 (Gitea #597): the published Primary data-plane verdict (<see cref="IDriverPrimaryRoleSource"/>
/// The published Primary data-plane verdict (<see cref="IDriverPrimaryRoleSource"/>
/// — the native-ack gate and the Sparkplug primary-host claim) must mirror <see cref="ShouldServiceAsPrimary"/>
/// from the moment this host starts, not only from the first redundancy snapshot. Before this, the view sat
/// on its single-node seed (allow) through the whole boot window, so on a pair BOTH nodes accepted a native
/// ack while this host — which evaluates the member count live — dropped the upstream route on the
/// non-Primary: the acked → unacked revert #597 targets. So publish once now, and again whenever cluster
/// non-Primary: the acked → unacked revert that the Primary gate prevents. So publish once now, and again whenever cluster
/// membership changes (a driver peer coming Up turns an unknown role from allow into deny before any
/// snapshot names this node). A non-cluster ActorRefProvider (legacy/test harnesses) just keeps the
/// initial publish.
@@ -915,7 +953,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// normally seconds, up to <c>Cluster:BootstrapGuard:PartnerProbeSeconds</c> (25 s) under the
/// bootstrap guard. In that pre-join window the Sparkplug primary-host claim can be held on both nodes of
/// a pair. Native ack is NOT exposed by it: the live route gate reads the same count and also allows, so
/// the view and the route still agree and the acked → unacked revert cannot occur (review R6 MINOR-2).
/// the view and the route still agree and the acked → unacked revert cannot occur.
/// Denying until self is Up was considered and NOT done: it would change the live data-plane gate (the
/// two must stay one decision) and so delay writes and acks on a genuinely single-node cluster during its
/// own join, and this actor has no reliable way to know that a partner is configured.
@@ -944,10 +982,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// own subscriber AFTER this event was delivered here — the two are not ordered.</summary>
private void OnDriverMembershipChanged(Akka.Cluster.ClusterEvent.IMemberEvent evt)
{
// Gitea #672: a member that comes Up at an address is reachable — the usual case being a restarted
// A member that comes Up at an address is reachable — the usual case being a restarted
// node's new incarnation. A REMOVED member deliberately stays in the set: it never answers again, and
// dropping it would re-derive the verdict from a cached snapshot that may still name it Primary,
// closing the gate on a dead node until the next snapshot (the very hole #672 closes).
// closing the gate on a dead node until the next snapshot (the very hole the reachability tracking closes).
if (evt is Akka.Cluster.ClusterEvent.MemberUp up
&& _unreachableNodes.Remove(ToNodeId(up.Member.Address)))
{
@@ -979,7 +1017,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
PublishPrimaryVerdict();
}
/// <summary>Gitea #674 review: publishes <see cref="PrimaryGatePolicy.ShouldServeHistoryUpdate"/> (no-op when no view
/// <summary>Publishes <see cref="PrimaryGatePolicy.ShouldServeHistoryUpdate"/> (no-op when no view
/// is wired). Rides every Primary-verdict publish point — host start, every snapshot, membership changes — so it is
/// closed from host start and opens only once a snapshot has arrived and the data-plane verdict allows.</summary>
private void PublishHistoryUpdateVerdict() =>
@@ -987,7 +1025,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
PrimaryGatePolicy.ShouldServeHistoryUpdate(_redundancySnapshotReceived, _localRole, DriverMemberCount()));
/// <summary>
/// Gitea #672: follow cluster reachability so the historization capture gate stops deferring to a recording
/// Follow cluster reachability so the historization capture gate stops deferring to a recording
/// Primary the failure detector already considers dead. Its OWN subscription, deliberately not folded into
/// <see cref="StartPrimaryVerdictPublishing"/>, which early-returns on nodes with no primary-role source.
/// <see cref="Akka.Cluster.ClusterEvent.MemberUp"/> rides along so a re-joined incarnation leaves the set.
@@ -1009,7 +1047,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
}
/// <summary>Gitea #672: a peer became unreachable or reachable again. Records it and re-derives ONLY the
/// <summary>A peer became unreachable or reachable again. Records it and re-derives ONLY the
/// historization capture verdict from the cached snapshot — the alarm drain and the Primary data-plane verdict
/// are deliberately untouched (a false allow there is a dual claimant, not a duplicate sample).</summary>
private void OnReachabilityChanged(Akka.Cluster.ClusterEvent.ReachabilityEvent evt)
@@ -1124,7 +1162,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// Per-cluster mesh Phase 4: condition state lives in the wired store — the replicated LocalDb
// store on a driver-role node, which persists with no ConfigDb. The ConfigDb-backed EF fallback
// was retired (Task 9); when no store was wired there is nowhere to persist condition state, so
// was retired; when no store was wired there is nowhere to persist condition state, so
// we skip the alarm host outright rather than run the engine against a store it can never save to
// (mirrors the _opcUaPublishActor-null skip above).
if (_alarmStateStore is null)
@@ -1267,7 +1305,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// cache boot, but this is the steady-state config source, not an outage fallback.
if (!ApplyCachedArtifact(deploymentId, cached.Artifact))
{
// #601 / review R1 m4: unusable cached bytes applied nothing, so they must not become the
// Unusable cached bytes applied nothing, so they must not become the
// current revision — that would ack a re-dispatch of the same revision as already applied
// without ever applying it. Steady-with-no-revision, exactly as for an empty cache.
_log.Warning(
@@ -1343,7 +1381,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
var deploymentId = DeploymentId.Parse(cached.DeploymentId);
var revision = RevisionHash.Parse(cached.RevisionHash);
// #601 / review R1 m4: unusable cached bytes applied nothing — the node is NOT serving a
// Unusable cached bytes applied nothing — the node is NOT serving a
// configuration, so it must not claim RUNNING FROM CACHE, adopt the revision (a re-dispatch of
// it would then be acked without being applied) or skip Stale's ConfigDb retry loop.
if (!ApplyCachedArtifact(deploymentId, cached.Artifact))
@@ -1389,12 +1427,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// depend on central.
/// </remarks>
/// <returns><see langword="false"/> when the bytes were empty or malformed and nothing was applied — the
/// caller must not adopt the cached revision (#601, review R1 m4).</returns>
/// caller must not adopt the cached revision.</returns>
private bool ApplyCachedArtifact(DeploymentId deploymentId, byte[] blob)
{
var correlation = CorrelationId.NewId();
// #601: null = the cached bytes were empty or malformed — no answer, not an empty configuration.
// Null = the cached bytes were empty or malformed — no answer, not an empty configuration.
// Keep last-known-good: no address-space rebuild and no subscription push from unusable bytes.
if (ReconcileDriversFromBlob(deploymentId, blob) is null)
return false;
@@ -1447,7 +1485,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private void Steady()
{
Receive<DispatchDeployment>(HandleDispatchFromSteady);
// #601 — the held Applied ack is released by the address-space outcome (or its timeout); both can
// The held Applied ack is released by the address-space outcome (or its timeout); both can
// land in any behaviour, so all three register them.
Receive<OpcUa.OpcUaPublishActor.RebuildCompleted>(HandleRebuildCompleted);
Receive<ApplyOutcomeTimedOut>(HandleApplyOutcomeTimedOut);
@@ -1563,7 +1601,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </summary>
private void ForwardBatchToMux(DriverInstanceActor.AttributeValueBatchPublished msg)
{
// One envelope per burst; the mux filters per item (it registered a batch receive in Task 9).
// One envelope per burst; the mux filters per item (it registered a batch receive).
_dependencyMux?.Tell(msg);
// 03/S15 recovery audit: clear whatever this burst re-published from the driver's Bad latch. Guarded
@@ -1628,7 +1666,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </para>
/// </summary>
/// <summary>
/// #477 — a child driver's connectivity transition. Annotates the source-data Quality of EVERY native
/// A child driver's connectivity transition. Annotates the source-data Quality of EVERY native
/// alarm condition the driver owns: comms lost → <see cref="OpcUaStatus.BadNoCommunication"/>, restored →
/// <see cref="OpcUaStatus.Good"/>. This is the ONLY signal for a comms-lost native source, because a
/// disconnected driver emits no alarm transitions — the alarm feed goes silent, so without this a
@@ -1642,8 +1680,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// (<see cref="IDriverHealthPublisher"/>); a row per condition would be alarm-fatigue.
/// </para>
/// <para>
/// <b>#481 (Layer 4) — the same transition also reaches SCRIPTED alarms, via the dependency
/// mux.</b> #478 gave a scripted condition the worst quality of its input tags, but only for
/// <b>Layer 4 — the same transition also reaches SCRIPTED alarms, via the dependency
/// mux.</b> A scripted condition already got the worst quality of its input tags, but only for
/// inputs whose driver actually <i>publishes</i> a Bad data change. A poll driver whose device
/// goes unreachable publishes nothing at all — it emits this signal and goes silent — so the
/// engine kept its last Good value, <c>WorstInputStatus</c> stayed Good, and worse,
@@ -1664,13 +1702,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </summary>
private void OnDriverConnectivityChanged(DriverInstanceActor.ConnectivityChanged msg)
{
// #481: the mux fan-out is independent of the OPC UA sink — a node with scripted alarms but no
// The mux fan-out is independent of the OPC UA sink — a node with scripted alarms but no
// publish actor (the mux-only test/dev path) must still see comms loss. Done before the early
// return for exactly that reason.
if (!msg.Connected)
{
FanCommsLossToDependencyMux(msg.DriverInstanceId);
// 03/S15: and the EXTERNAL data plane, which #481 stopped one seam short of.
// And the EXTERNAL data plane, which the dependency-mux fan-out stopped one seam short of.
FanCommsLossToValueNodes(msg.DriverInstanceId);
}
else
@@ -1682,7 +1720,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
if (_opcUaPublishActor is null) return;
// #519: name the actual cause. This is a connectivity transition, so the Bad case is
// Name the actual cause. This is a connectivity transition, so the Bad case is
// BadNoCommunication — the bare OpcUaQuality.Bad it used to send reached clients as 0x80000000,
// indistinguishable from any other fault.
var statusCode = msg.Connected ? OpcUaStatus.Good : OpcUaStatus.BadNoCommunication;
@@ -1718,7 +1756,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </summary>
/// <remarks>
/// <para>
/// <b>Why it was missing.</b> #481 built the per-driver ref index and wired comms loss to the
/// <b>Why it was missing.</b> The per-driver ref index was built and wired comms loss to the
/// internal consumers (the mux) and to Part 9 conditions, and stopped one seam short of the
/// external OPC UA data plane. A client subscribed to a value node therefore saw the last value
/// at <b>Good</b> quality for the whole outage, for every driver whose failure shape is "the
@@ -1832,7 +1870,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// observed — the very thing this whole path refuses to do. What the operator gets instead is a
/// named driver and a count, plus the <c>otopcua.driver.comms_latched_refs</c> counter, which is
/// the operator-visible signature of a driver that reconnects without re-publishing (the
/// pre-STAB-18 MQTT shape, or any future push driver that forgets its initial push).
/// MQTT shape, or any future push driver that forgets its initial push).
/// </para>
/// <para>
/// The latch is cleared afterwards either way: it has been reported, and leaving it would make
@@ -1865,13 +1903,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
/// <summary>
/// #481 (Layer 4) — push a synthetic <see cref="OpcUaStatus.BadNoCommunication"/> into the dependency
/// Layer 4 — push a synthetic <see cref="OpcUaStatus.BadNoCommunication"/> into the dependency
/// mux for every value ref the just-disconnected driver owns, so scripted alarms and virtual tags see
/// the source die instead of holding its last Good value indefinitely.
/// </summary>
/// <remarks>
/// <para>
/// <b>The ref set already existed.</b> #481 asked for a driver → all-tag-refs map to be built;
/// <b>The ref set already existed.</b> The fan-out needed a driver → all-tag-refs map to be built;
/// <see cref="_nodeIdByDriverRef"/> is exactly that, keyed <c>(DriverInstanceId, RawPath)</c> and
/// rebuilt from the composition's <c>RawTags</c> ∪ <c>UnsReferenceVariables</c> on every apply —
/// read here through the per-driver <see cref="_valueRefsByDriver"/> index, since that composite
@@ -1884,7 +1922,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <b>Value <c>null</c>, not the last-known value.</b> The honest statement is "there is no
/// current value", and the engine's <c>AreInputsReady</c> gate holds the predicate on any Bad
/// regardless, so no script observes the null. It does mean the Bad must survive
/// <c>WorstInputStatus</c>, which until #481 skipped every null-valued entry as cold start —
/// <c>WorstInputStatus</c>, which used to skip every null-valued entry as cold start —
/// hence the paired change stamping never-pushed paths <c>BadWaitingForInitialData</c> so the two
/// are tellable apart. Without that half this fan-out would be silently inert.
/// </para>
@@ -1953,8 +1991,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
return;
}
// #626 — a QUALITY-ONLY annotation (an MTConnect condition gone Unavailable, or back) is not an alarm
// transition. It rides the SAME quality-only node path the #477 connectivity annotation uses
// A QUALITY-ONLY annotation (an MTConnect condition gone Unavailable, or back) is not an alarm
// transition. It rides the SAME quality-only node path the connectivity annotation uses
// (AlarmQualityUpdate → WriteAlarmQuality, which touches Quality and nothing else), never a projected
// snapshot: the projector never sees a client's acknowledgement (that is applied to the node by the
// SDK) and forgets a condition a deploy removed, so a projected "keep the state" can disagree with
@@ -1995,11 +2033,11 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
nodeId, snapshot, msg.Args.SourceTimestampUtc, n.Realm));
// Only the Primary publishes the cluster-wide alerts transition (see the gate above). The projector
// decides WHICH rows the transition warrants: none for a re-statement (Gitea #647 review: a Raise on an
// already-active condition from a respawned driver; #656: a flagged snapshot/first-sight Retrigger or
// Clear that changes nothing the condition shows), and up to two for an ActiveAcknowledged (#656:
// decides WHICH rows the transition warrants: none for a re-statement (a Raise on an
// already-active condition from a respawned driver; a flagged snapshot/first-sight Retrigger or
// Clear that changes nothing the condition shows), and up to two for an ActiveAcknowledged (
// "Activated" only if it was not already active, "Acknowledged" only if it was not already acked) or an
// InactiveUnacknowledged (#657: "Activated" + "Cleared" only if it was acked, "Cleared" if it was active).
// InactiveUnacknowledged ("Activated" + "Cleared" only if it was acked, "Cleared" if it was active).
if (!serviceAlertsAsPrimary) continue;
var meta = _alarmMetaByNodeId.TryGetValue(nodeId, out var m)
@@ -2023,9 +2061,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
(string EquipmentId, string Name, string AlarmType, bool? HistorizeToAveva, IReadOnlyList<string> ReferencingEquipmentPaths) meta,
AlarmTransitionKind historyKind)
{
// #656: an ActiveAcknowledged expands to "Activated" + "Acknowledged". The operator comment/user belong to
// An ActiveAcknowledged expands to "Activated" + "Acknowledged". The operator comment/user belong to
// the acknowledgement, and the activation happened at the original raise time when the source knows it.
// #657: an InactiveUnacknowledged's "Activated" row is likewise the occurrence, at its raise time when known.
// An InactiveUnacknowledged's "Activated" row is likewise the occurrence, at its raise time when known.
var expandedActivation = (args.Kind == AlarmTransitionKind.ActiveAcknowledged
&& historyKind != AlarmTransitionKind.Acknowledge)
|| (args.Kind == AlarmTransitionKind.InactiveUnacknowledged && historyKind == AlarmTransitionKind.Raise);
@@ -2051,7 +2089,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// true and suppresses the durable AVEVA row only on an explicit false — the same posture as the
// scripted-alarm opt-out. null here rides through unchanged (the gate treats it as default-on).
HistorizeToAveva: meta.HistorizeToAveva,
// WP4: the Area/Line/Equipment UNS paths that reference this raw condition — the /alerts row
// The Area/Line/Equipment UNS paths that reference this raw condition — the /alerts row
// renders them as the equipment list (empty for a raw condition no equipment references yet).
ReferencingEquipmentPaths: meta.ReferencingEquipmentPaths);
_mediator.Tell(new Publish(ScriptedAlarmHostActor.AlertsTopic, alertEvent));
@@ -2071,9 +2109,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
AlarmTransitionKind.Raise or AlarmTransitionKind.Retrigger => "Activated",
AlarmTransitionKind.Clear => "Cleared",
AlarmTransitionKind.Acknowledge => "Acknowledged",
// #656: never reached in practice — the projector expands ActiveAcknowledged into Raise + Acknowledge rows.
// Never reached in practice — the projector expands ActiveAcknowledged into Raise + Acknowledge rows.
AlarmTransitionKind.ActiveAcknowledged => "Acknowledged",
// #657: likewise never reached — expanded into Raise + Clear (or Clear alone) rows.
// Likewise never reached — expanded into Raise + Clear (or Clear alone) rows.
AlarmTransitionKind.InactiveUnacknowledged => "Cleared",
_ => "Activated",
};
@@ -2215,7 +2253,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
return;
}
// Gitea #641 review — the node is already acknowledged (the SDK applies the client's ack); tell the
// The node is already acknowledged (the SDK applies the client's ack); tell the
// projector too, or the next driver Clear projects (Active=false, Acked=prev=false) and un-acknowledges it.
// Most sources (MTConnect, FOCAS) send no Acknowledge transition back, and the projector now survives a
// deploy rather than resetting to its acked default.
@@ -2250,8 +2288,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
if (_driverMemberCountProvider is not null) return _driverMemberCountProvider();
try
{
// R3-04 (01/C-9): GossipedRolesHave, not ordinal Contains — a peer gossiping a miscased
// 'Driver' (rolling-upgrade window) must still count toward the R2-04 primary-gate member
// GossipedRolesHave, not ordinal Contains — a peer gossiping a miscased
// 'Driver' (rolling-upgrade window) must still count toward the primary-gate member
// count, or a genuine 2-node pair silently takes the single-node allow branch.
return Akka.Cluster.Cluster.Get(Context.System).State.Members
.Count(m => m.Status == Akka.Cluster.MemberStatus.Up
@@ -2264,7 +2302,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
/// <summary>Whether <paramref name="nodeId"/> holds this node's replicated alarm queue: the PeerAddress host when
/// this node dials, else the passive-half predicate (review R6 MINOR-4). This node itself never counts.</summary>
/// this node dials, else the passive-half predicate. This node itself never counts.</summary>
private bool SharesAlarmQueue(CommonsNodeId nodeId) =>
nodeId != _localNode
&& (_replicationPeerHost is not null
@@ -2322,15 +2360,15 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// cluster-wide and the queue is pair-local, so "somebody is Primary" is not a licence to stop
// draining — that Primary is usually in another pair entirely, and cannot deliver our events.
//
// The dialling half knows its peer by PeerAddress host. The passive half (review R6 MINOR-4) knows it
// The dialling half knows its peer by PeerAddress host. The passive half knows it
// only as its mesh partner — the predicate — and must be gated too, or both halves drain the same rows.
var peerIsPrimary = msg.Nodes.Any(n => n.Role == RedundancyRole.Primary && SharesAlarmQueue(n.NodeId));
_redundancyRoleView?.Publish(
PrimaryGatePolicy.ShouldDrainAlarmHistory(_localRole, queueSharingPeerIsPrimary: peerIsPrimary));
// Gitea #537: the continuous-historization CAPTURE verdict. Same role rule as the drain gate
// above, but a different peer question — see ComputeHistorizationVerdict. Cached (#672) so a
// The continuous-historization CAPTURE verdict. Same role rule as the drain gate
// above, but a different peer question — see ComputeHistorizationVerdict. Cached so a
// reachability change can re-derive it before the next snapshot arrives.
_lastRedundancySnapshotNodes = msg.Nodes;
if (_historizationRoleView is not null)
@@ -2342,13 +2380,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// The DATA-PLANE verdict, deliberately — the same one HandleRouteNodeWrite gates on, not the
// drain verdict published immediately above. A driver reading this claims an exclusive identity
// on a shared external system (Gitea #511: the Sparkplug host id), where two claimants is the
// on a shared external system (the Sparkplug host id), where two claimants is the
// harm, so an unknown role with a driver peer present must deny.
PublishPrimaryVerdict();
}
/// <summary>
/// The continuous-historization capture verdict for a snapshot (Gitea #537, #672).
/// The continuous-historization capture verdict for a snapshot.
/// </summary>
/// <remarks>
/// <para>Historization is not pair-local, it is fleet-wide by historian tag name, so the only node worth
@@ -2356,12 +2394,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// no way to establish that (a legacy node carrying no cluster-scoped role, or a test harness), the
/// predicate is null and this node keeps capturing. Duplicate samples are recoverable; a hole in the trend
/// is not.</para>
/// <para><b>#672 — an UNREACHABLE recording Primary does not count.</b> A crashed (SIGKILLed) Primary stays a
/// <para><b>An UNREACHABLE recording Primary does not count.</b> A crashed (SIGKILLed) Primary stays a
/// cluster member until auto-down, and the redundancy singleton usually died with it, so the cached snapshot
/// keeps naming it Primary for the whole failure-detector + auto-down window (~25 s) while nobody captures.
/// Excluding unreachable peers shrinks that hole to the failure-detector window alone. The cost — a short
/// duplicate window, and both nodes capturing for the duration of a genuine partition — is the same
/// asymmetric trade #537 already makes. Gated by <c>ContinuousHistorization:CaptureWhilePrimaryUnreachable</c>.</para>
/// asymmetric trade the capture gate already makes. Gated by <c>ContinuousHistorization:CaptureWhilePrimaryUnreachable</c>.</para>
/// </remarks>
private bool ComputeHistorizationVerdict(IReadOnlyList<NodeRedundancyState> nodes)
{
@@ -2434,7 +2472,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// The redundancy-state topic also carries OpcUaProbeResult (OpcUaPublishActor peer-probes).
// We don't consume it here — drop it so it doesn't dead-letter (matches PeerProbeSupervisor).
Receive<ZB.MOM.WW.OtOpcUa.Runtime.Health.PeerOpcUaProbeActor.OpcUaProbeResult>(_ => { });
// #601 — an apply that completed just before the host went Stale still owes its ack; the
// An apply that completed just before the host went Stale still owes its ack; the
// coordinator is not behind the ConfigDb, so release it exactly as in Steady.
Receive<OpcUa.OpcUaPublishActor.RebuildCompleted>(HandleRebuildCompleted);
Receive<ApplyOutcomeTimedOut>(HandleApplyOutcomeTimedOut);
@@ -2480,7 +2518,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private void HandleDispatchFromSteady(DispatchDeployment msg)
{
// #601: the short-circuit claims a CLEAN Applied, so it is only honest while the current revision's
// The short-circuit claims a CLEAN Applied, so it is only honest while the current revision's
// address space is known-good — not after a degraded apply, and not while its outcome is still
// pending. Either way the dispatch re-applies instead, which is also what repairs a degraded apply.
var currentRevisionUnconfirmed = _currentRevisionDegraded
@@ -2547,7 +2585,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_log.Debug("DriverHost {Node}: fetching artifact for {Id} (rev {Rev}) from central over gRPC",
_localNode, deploymentId, revision);
// A faulted fetch task maps to null bytes — the #485 apply-failure path, exactly like an
// A faulted fetch task maps to null bytes — the apply-failure path, exactly like an
// all-endpoints-down fetch — so a fault can never escape as an unhandled actor message.
_artifactFetcher.FetchAsync(deploymentId.ToString(), revision.Value, CancellationToken.None)
.PipeTo(
@@ -2559,7 +2597,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
/// <summary>
/// Perf roadmap Task 26 (<c>Direct</c>). Kicks off the central-SQL artifact read on a pool
/// Direct apply path. Kicks off the central-SQL artifact read on a pool
/// thread and pipes the bytes back to <see cref="Self"/> as an <see cref="ArtifactForApply"/>,
/// the same shape <see cref="BeginFetchAndCacheApply"/> has always had for its gRPC fetch. The
/// apply itself completes on the actor thread in <see cref="HandleArtifactForApply"/>.
@@ -2573,7 +2611,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// source ever should — everything downstream of "bytes in hand" is one continuation.
/// </para>
/// <para>
/// The bytes come back as a MESSAGE, never as an escaping fault (#491): the task closes over
/// The bytes come back as a MESSAGE, never as an escaping fault: the task closes over
/// <see cref="_dbFactory"/>, <see cref="_localNode"/> and <see cref="_log"/> and touches
/// neither <see cref="Self"/> nor <c>Context</c>, <see cref="LoadArtifactBlob"/> already
/// swallows its own DB failures into a null return, and the failure mapper turns anything it
@@ -2607,7 +2645,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <summary>
/// Completes an apply once the artifact bytes are in hand — the ONE continuation both modes
/// share, whether the bytes were read from the ConfigDb or fetched from central. Null bytes are
/// an apply FAILURE (keep last-known-good, do not advance the revision — #485/#486); non-null
/// an apply FAILURE (keep last-known-good, do not advance the revision); non-null
/// bytes are applied from hand and cached.
/// </summary>
private void HandleArtifactForApply(ArtifactForApply msg)
@@ -2631,7 +2669,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
ParsedDeploymentArtifact? parsed = null;
try
{
// #485/#486: null bytes = "no answer" — the ConfigDb was unreachable or the row is
// Null bytes = "no answer" — the ConfigDb was unreachable or the row is
// missing/empty (Direct), or every endpoint was unreachable / NotFound / SHA mismatch
// (FetchAndCache). Either way NOTHING was applied, so fail the apply and stay on the
// current revision: HandleDispatchFromSteady short-circuits on a revision match, so
@@ -2658,7 +2696,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_currentRevision = msg.Revision;
UpsertNodeDeploymentState(msg.DeploymentId, NodeDeploymentStatus.Applied, failureReason: null);
// Gitea #601: the Applied ack is NOT sent here any more. It used to go out right now, before the
// The Applied ack is NOT sent here any more. It used to go out right now, before the
// address-space apply below had even been dequeued, so a degraded apply (swallowed sink faults,
// _lastApplied not advanced) still sealed the deployment green fleet-wide. The ack is now held
// until OpcUaPublishActor replies RebuildCompleted (HandleRebuildCompleted) or the outcome
@@ -2700,7 +2738,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
catch (Exception ex)
{
// #601: a throw after the Applied ack was put on hold — the Failed ack below is this apply's one
// A throw after the Applied ack was put on hold — the Failed ack below is this apply's one
// answer, so the held Applied must never follow it when the address-space outcome lands.
DropPendingAck(msg.Correlation);
UpsertNodeDeploymentState(msg.DeploymentId, NodeDeploymentStatus.Failed, ex.Message);
@@ -2723,19 +2761,19 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
}
/// <summary>Gitea #601 — an Applied ack held until the address-space apply reports its outcome.</summary>
/// <summary>An Applied ack held until the address-space apply reports its outcome.</summary>
private sealed record PendingAck(DeploymentId DeploymentId, RevisionHash Revision, CorrelationId Correlation);
/// <summary>Gitea #601 — self-timer: the address-space outcome for this correlation did not arrive in time.</summary>
/// <summary>Self-timer: the address-space outcome for this correlation did not arrive in time.</summary>
private sealed record ApplyOutcomeTimedOut(CorrelationId Correlation);
private static string ApplyOutcomeTimerKey(CorrelationId correlation) => $"apply-outcome-{correlation}";
/// <summary>
/// Gitea #601 — holds the Applied ack for an apply whose revision has just advanced until the
/// Holds the Applied ack for an apply whose revision has just advanced until the
/// address-space apply outcome is known, arming <see cref="_applyOutcomeTimeout"/> as the backstop.
/// With no publish actor wired (tests, a node with no OPC UA data plane) there is no outcome to wait
/// for, so the ack is sent clean at once — byte-for-byte the pre-#601 behaviour.
/// for, so the ack is sent clean at once — byte-for-byte the earlier behaviour.
/// </summary>
private void AwaitAddressSpaceOutcomeThenAck(DeploymentId deploymentId, RevisionHash revision, CorrelationId correlation)
{
@@ -2754,7 +2792,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
Timers.StartSingleTimer(ApplyOutcomeTimerKey(correlation), new ApplyOutcomeTimedOut(correlation), _applyOutcomeTimeout);
}
/// <summary>Gitea #601 — forgets a held ack (its apply failed after all, and acks Failed instead).</summary>
/// <summary>Forgets a held ack (its apply failed after all, and acks Failed instead).</summary>
private void DropPendingAck(CorrelationId correlation)
{
if (_pendingAcks.Remove(correlation))
@@ -2762,7 +2800,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
/// <summary>
/// Gitea #601 — the address-space apply reported its outcome: release the held ack, clean or
/// The address-space apply reported its outcome: release the held ack, clean or
/// degraded. Registered in every behaviour (Steady, Applying, Stale) because the reply can land in
/// any of them — the host returns to Steady before the publish actor has even dequeued the rebuild.
/// </summary>
@@ -2780,7 +2818,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
/// <summary>
/// Gitea #601 — the address-space outcome did not arrive within <see cref="_applyOutcomeTimeout"/>.
/// The address-space outcome did not arrive within <see cref="_applyOutcomeTimeout"/>.
/// The ack is sent anyway so the coordinator does not time the deployment out on a node that DID
/// advance its revision — but degraded, never clean: nobody has confirmed the address space.
/// </summary>
@@ -2801,7 +2839,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
if (degraded)
{
// #601 review — the apply wrote this node's own row Applied/null before the outcome was known. Central
// The apply wrote this node's own row Applied/null before the outcome was known. Central
// adds the reason from the ack only when it ACCEPTS the ack (a timed-out or superseded deployment's ack
// is discarded), so a node with a ConfigDb records it itself; a driver-only node no-ops here.
UpsertNodeDeploymentState(pending.DeploymentId, NodeDeploymentStatus.Applied,
@@ -2872,7 +2910,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// Read the deployment artifact + reconcile the set of running <see cref="DriverInstanceActor"/>
/// children. Spawn missing, respawn on config change, stop removed/disabled drivers.
/// When the artifact blob is empty (legacy ControlPlane tests, smoke fixtures) the reconcile is
/// SKIPPED outright — see the issue #485 guard below — and when the configured
/// SKIPPED outright — see the empty-artifact guard below — and when the configured
/// <see cref="IDriverFactory"/> can't materialise any of the requested types this is a no-op.
/// </summary>
/// <returns>
@@ -2907,7 +2945,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <remarks>
/// Called on the actor thread by the PreStart restore path and on a POOL thread by
/// <see cref="BeginDirectApply"/>, so it must stay free of <see cref="Self"/> / <c>Context</c>
/// (#491). It touches only <see cref="_dbFactory"/>, <see cref="_localNode"/> and
/// It touches only <see cref="_dbFactory"/>, <see cref="_localNode"/> and
/// <see cref="_log"/>, all of which are safe off the actor thread — the logger publishes to the
/// EventStream and captures nothing from the cell.
/// </remarks>
@@ -2917,7 +2955,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
{
// Phase 4 belt-and-suspenders: this ConfigDb read is Direct-only (the FetchAndCache apply uses
// ReconcileDriversFromParsed with bytes in hand). A null factory can't read, so return null — the
// caller treats that as "artifact could not be read" (#486) and keeps last-known-good.
// caller treats that as "artifact could not be read" and keeps last-known-good.
if (_dbFactory is null)
{
_log.Warning("DriverHost {Node}: no ConfigDb to load artifact for {Id}; skipping reconcile", _localNode, deploymentId);
@@ -2948,7 +2986,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// below async, and the only caller-side token is actor lifetime — the timeout gives the same
// bound without touching the actor seam. A timeout surfaces as an exception through this
// method's existing catch-to-null, so the apply FAILS and the revision does not advance,
// keeping last-known-good served (the #485-family "no answer, never tear down" semantics —
// keeping last-known-good served (the "no answer, never tear down" semantics —
// already correct, unchanged here).
//
// Guarded on IsRelational: the timeout is a relational-only concept and the extension throws
@@ -2975,7 +3013,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <summary>
/// An apply's artifact: the bytes that were reconciled plus the ONE
/// <see cref="ParsedDeploymentArtifact"/> every later consumer of that apply reads. Both are
/// <see langword="null"/> when nothing was applied (#485/#486).
/// <see langword="null"/> when nothing was applied.
/// </summary>
/// <param name="Blob">The reconciled artifact bytes, or null when there was no usable artifact.</param>
/// <param name="Parsed">The parsed artifact, owned by the apply handler — dispose before it returns.</param>
@@ -2989,7 +3027,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// apply builds exactly one <c>JsonDocument</c> in this actor.
/// </summary>
/// <returns>The reconciled blob + its parsed artifact, or a default (both null) when the blob was
/// empty or absent (#485).</returns>
/// empty or absent.</returns>
/// <exception cref="System.Text.Json.JsonException">The artifact bytes are not valid JSON. Unlike the
/// lenient blob wrappers (malformed ⇒ no specs ⇒ every running child planned for StopChild) this
/// surfaces, and <see cref="HandleArtifactForApply"/>'s catch turns it into a Failed ACK with the
@@ -3027,7 +3065,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// "malformed ⇒ no specs" parse those paths have always had. The apply paths use
/// <see cref="ReconcileDriversFromParsed"/> instead, so they parse once and keep the parse.
/// </summary>
/// <returns>The reconciled blob, or <see langword="null"/> when it was empty (#485).</returns>
/// <returns>The reconciled blob, or <see langword="null"/> when it was empty.</returns>
private byte[]? ReconcileDriversFromBlob(DeploymentId deploymentId, byte[]? blob)
{
blob ??= Array.Empty<byte>();
@@ -3037,7 +3075,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
return null;
}
// #601 (S-10): non-empty but malformed bytes are "no answer" too. The lenient static
// Non-empty but malformed bytes are "no answer" too. The lenient static
// ParseDriverInstances swallows the JsonException into an empty list, and an empty list plans every
// running child for StopChild. Open throws instead, so a corrupt cache row / restored blob leaves
// the running drivers alone, exactly like the zero-length case above.
@@ -3060,7 +3098,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
/// <summary>
/// Issue #485 — no bytes is no answer, not "a configuration with no drivers". Parsing zero bytes
/// No bytes is no answer, not "a configuration with no drivers". Parsing zero bytes
/// yields zero specs, and <c>DriverSpawnPlanner</c> then plans EVERY running child for StopChild: a
/// missing deployment row (or a half-written one) silently takes this node's entire field I/O down
/// while the apply still ACKs Applied. Nothing legitimate produces a zero-length blob — deleting the
@@ -3085,9 +3123,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
foreach (var id in plan.ToStop) StopChild(id);
foreach (var spec in plan.ToSpawn) SpawnChild(spec);
// v3 (WP7): a dependency-consumer driver's declared dependency refs change when its tags/scripts are
// edited. That edit changes its DriverConfig, which respawns it (#516), and the respawned driver's
// adapter registers the NEW set in PreStart — no separate re-register is needed (#665).
// v3: a dependency-consumer driver's declared dependency refs change when its tags/scripts are
// edited. That edit changes its DriverConfig, which respawns it, and the respawned driver's
// adapter registers the NEW set in PreStart — no separate re-register is needed.
}
/// <summary>
@@ -3327,7 +3365,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </remarks>
private void PushDesiredSubscriptionsFromArtifact(DeploymentId deploymentId, byte[] blob)
{
// Issue #485 — the same "no bytes is no answer" rule as ReconcileDrivers. An empty artifact parses
// The same "no bytes is no answer" rule as ReconcileDrivers. An empty artifact parses
// to a composition with no raw tags, which hands every child an EMPTY desired set — and an empty set
// drops the live subscription handle rather than re-subscribing. Reachable independently of the
// reconcile guard: this method does its OWN ConfigDb read, so the row can go missing between the two.
@@ -3339,7 +3377,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
return;
}
// #601 (S-10): Open, not the lenient static ParseComposition — that wrapper swallows malformed JSON
// Open, not the lenient static ParseComposition — that wrapper swallows malformed JSON
// into an EMPTY composition, which would hand every child an empty desired set and drop its live
// subscription. A malformed artifact is no answer: leave the subscriptions as they are.
AddressSpaceComposition composition;
@@ -3449,7 +3487,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_alarmNodeIdByDriverRef.Clear();
_driverRefByAlarmNodeId.Clear();
_alarmMetaByNodeId.Clear();
// NOT _nativeAlarmProjector.Clear() (Gitea #641): it is pruned to the still-deployed conditions after the
// NOT _nativeAlarmProjector.Clear(): it is pruned to the still-deployed conditions after the
// maps are rebuilt below, so a redeploy that keeps an alarm keeps its projected prior state.
// The per-driver secondary indexes are rebuilt WHOLE alongside their primaries below — same pass,
// same clear — so no incremental maintenance exists to get out of step with them.
@@ -3460,8 +3498,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
var key = (t.DriverInstanceId, t.NodeId); // (DriverInstanceId, RawPath) — RawPath IS the wire-ref
if (t.Alarm is not null)
{
// Native alarm → a single Part 9 condition at the RawPath (Raw realm). WP4 adds the referencing
// equipment notifier NodeIds; WP3 wires the single raw condition.
// Native alarm → a single Part 9 condition at the RawPath (Raw realm). The referencing
// equipment notifier NodeIds are added on top of the single raw condition.
if (!_alarmNodeIdByDriverRef.TryGetValue(key, out var aset))
{
_alarmNodeIdByDriverRef[key] = aset = new HashSet<NodeRealmRef>();
@@ -3473,8 +3511,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
aset.Add(new NodeRealmRef(t.NodeId, AddressSpaceRealm.Raw));
// Inverse 1:1 map for the inbound native-condition ack path (keyed by BARE condition NodeId).
_driverRefByAlarmNodeId[t.NodeId] = key;
// Per-condition metadata for the alerts fan-out. WP4 refines /alerts identity to the referencing
// equipment paths; WP3 keys the display off the RawPath. The referencing-equipment paths (the
// Per-condition metadata for the alerts fan-out. The /alerts identity is refined to the referencing
// equipment paths; the display is keyed off the RawPath. The referencing-equipment paths (the
// Area/Line/Equipment UNS folder paths carried on the RawTagPlan) ride onto every transition so
// the /alerts row lists which equipment reference this raw condition.
_alarmMetaByNodeId[t.NodeId] = (t.NodeId, t.Name, t.Alarm.AlarmType, t.Alarm.HistorizeToAveva, t.ReferencingEquipmentPaths);
@@ -3504,7 +3542,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
}
// Gitea #641 — forget the projected prior state of conditions this composition no longer carries, and keep
// Forget the projected prior state of conditions this composition no longer carries, and keep
// the rest. Clearing it whole on every apply made the next driver Acknowledge of a still-active alarm
// project Active=false (the default prior), and the next Clear of an unacknowledged one project
// Acked=true — on any deploy, rebuild or not. The node manager carries the NODE's state across a rebuild,
@@ -3596,7 +3634,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private void SpawnChild(DriverInstanceSpec spec)
{
// #609: an instance id removed by an earlier deployment (StopChild ⇒ Evict, which also holds back late
// An instance id removed by an earlier deployment (StopChild ⇒ Evict, which also holds back late
// items) may come back; lift the hold BEFORE the child exists, since it publishes health as it starts.
// The resilience tracker's equivalent is lifted by _invokerFactory.Create below.
_telemetryHub?.Readmit(spec.DriverInstanceId);
@@ -3609,7 +3647,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
{
// A factory throw is a CONFIG error, not a connectivity one — TryCreate is pure parsing;
// device I/O happens later in InitializeAsync. Logged at Error because the node silently
// degrades to a stub that answers nothing, and since #516 routed DriverConfig changes
// degrades to a stub that answers nothing, and since DriverConfig changes are now routed
// through a respawn this path is now reachable by an ordinary operator edit rather than
// only by a brand-new driver. It still does NOT fail the deployment — making it do so is
// a deliberate follow-up, since it would let one malformed driver block a fleet deploy.
@@ -3673,12 +3711,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// supervision reprovision. Sending it HERE rather than at each call site is the point: a child that
// exists without its subscription set is a dead driver, so the two facts are established together.
// Before this, the only sender was the apply's bulk push, so an operator's Restart produced a child
// that connected and then read nothing until the next deployment — the #488 periodic reconcile cannot
// that connected and then read nothing until the next deployment — the periodic reconcile cannot
// help, because it early-returns on an empty desired set.
//
// ORDERING, and its one accepted cost: ApplyDriverSpecs (which spawns) runs BEFORE
// ApplyDesiredSubscriptions (which rebuilds _desiredByDriver), so on a deploy that RESPAWNS a child
// (#516 — the merged DriverConfig folds in the raw tags, so a tag-set edit changes the spec) the new
// (the merged DriverConfig folds in the raw tags, so a tag-set edit changes the spec) the new
// child is handed the PREVIOUS apply's set, and nothing at all on the first deploy. That transient is
// superseded a moment later by the bulk push, on the same sender→receiver pair, so Akka's per-pair
// ordering guarantees the child CONVERGES on the new set — but it is NOT guaranteed to be inert on
@@ -3692,7 +3730,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// Sent after InitializeRequested above, which keeps init-before-subscribe ordering.
SendDesiredSubscriptions(child, spec.DriverInstanceId);
// v3 (WP7): if the (real, non-stub) driver consumes other tags' live values, spawn a mux-adapter
// v3: if the (real, non-stub) driver consumes other tags' live values, spawn a mux-adapter
// child that registers its dependency refs on the per-node dependency mux and forwards changes
// into the driver. Requires a wired mux (dev/None deployments have none — then calc inputs simply
// can't flow, matching the VirtualTag dev path).
@@ -3724,7 +3762,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
StopDependencyAdapter(driverInstanceId);
Context.Stop(entry.Actor);
_children.Remove(driverInstanceId);
// #609: the instance left the plan (StopChild is only reached via plan.ToStop), so its cached
// The instance left the plan (StopChild is only reached via plan.ToStop), so its cached
// Health/Resilience snapshots must not replay to new telemetry subscribers. Release the shared
// resilience state FIRST: the resilience publisher re-emits the tracker's snapshots every tick, so
// evicting the hub alone was undone within one interval. Context.Stop is asynchronous, so the child can
@@ -3828,7 +3866,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// be in flight from an OLD incarnation after HandleRestartDriver stopped that child and spawned a
// replacement under the same DriverInstanceId. Delivered to the new child — which is in Connecting,
// where InitializeRequested IS handled — it would start a second, concurrent InitializeAsync,
// racing the dispose-before-overwrite that #527's teardown exists to serialise
// racing the dispose-before-overwrite that the teardown exists to serialise
// (ModbusDriver._transport, MqttDriver._connection each leak a transport on that race).
if (!Equals(child, entry.Actor))
{
@@ -3948,7 +3986,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
{
// Synchronous by design, and a recorded follow-up rather than an oversight: this is a
// bounded per-apply write of ONE row (at most three per deployment), not the multi-MB
// artifact read that Task 26 moved off the mailbox. It is also the apply's crash-boundary
// artifact read that moved off the mailbox. It is also the apply's crash-boundary
// marker, which is easiest to reason about while it is ordered on the actor thread.
using var db = _dbFactory.CreateDbContext();
var existing = db.NodeDeploymentStates.FirstOrDefault(
@@ -36,7 +36,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
public sealed record InitializeSucceeded(int Generation);
public sealed record InitializeFailed(string Reason, int Generation);
public sealed record DisconnectObserved(string Reason);
/// <summary>#477 — sent to the parent (<see cref="DriverHostActor"/>) on every connectivity transition:
/// <summary>Sent to the parent (<see cref="DriverHostActor"/>) on every connectivity transition:
/// <c>Connected=true</c> on entering the Connected state, <c>false</c> on entering Reconnecting. The host
/// annotates this driver's native alarm conditions' source-data Quality from it (comms lost → Bad,
/// restored → Good) — independently of alarm transitions, since a comms-lost driver emits no alarm
@@ -44,8 +44,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected);
/// <summary>
/// Sent to the parent from <see cref="PostRestart"/> so the host re-provisions THIS incarnation
/// (archreview 03/S6, 03/S16).
/// Sent to the parent from <see cref="PostRestart"/> so the host re-provisions THIS incarnation.
/// </summary>
/// <remarks>
/// A supervision restart recreates the actor object in place: the desired subscription sets are gone
@@ -113,7 +112,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// (<c>DriverHostActor.FanCommsLossToDependencyMux</c>), which was the last sender to fabricate this
/// message, now fabricates a batch too. The dependency mux still accepts it for tests and direct senders.
/// <para><paramref name="StatusCode"/> is the driver's full OPC UA status code including its sub-code
/// (#519) — not a severity bucket. Classify it with <see cref="OpcUaStatus.IsGood"/> and friends rather
/// — not a severity bucket. Classify it with <see cref="OpcUaStatus.IsGood"/> and friends rather
/// than comparing it to <see cref="OpcUaStatus.Good"/>.</para></summary>
public sealed record AttributeValuePublished(string DriverInstanceId, string FullReference, object? Value, uint StatusCode, DateTime TimestampUtc);
/// <summary>One value within an <see cref="AttributeValueBatchPublished"/>.
@@ -123,7 +122,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
public readonly record struct AttributeValueItem(string FullReference, object? Value, uint StatusCode, DateTime TimestampUtc);
/// <summary>Batched form of <see cref="AttributeValuePublished"/> — every changed attribute of ONE
/// driver production burst in one message. The parent fans the whole batch to the mux and the OPC UA
/// publish path in one hop each. Status codes ride verbatim (#519).</summary>
/// publish path in one hop each. Status codes ride verbatim.</summary>
public sealed record AttributeValueBatchPublished(string DriverInstanceId, IReadOnlyList<AttributeValueItem> Items);
private sealed record DataChangeForward(string FullReference, DataValueSnapshot Snapshot);
/// <summary>Self-sent when a batch-capable driver (<see cref="IBatchSubscribable"/>) raises
@@ -153,9 +152,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// behaviour for the same reason as <see cref="RediscoveryRaised"/> — a probe tick can land while the
/// driver is between connects.</summary>
private sealed record HostStatusRaised;
/// <summary>Self-sent when the wrapped driver raises <see cref="IDriverConnectionLossSource.ConnectionLost"/> (#676)
/// <summary>Self-sent when the wrapped driver raises <see cref="IDriverConnectionLossSource.ConnectionLost"/>
/// — it KNOWS its connection is gone for good. Marshals the event off the driver's thread. Acted on only in
/// Connected (it becomes a disconnect at once, instead of after the #527 watchdog's silence window); every other
/// Connected (it becomes a disconnect at once, instead of after the watchdog's silence window); every other
/// behaviour is already reconnecting or connecting and ignores it.</summary>
private sealed record ConnectionLossRaised(DriverConnectionLossEventArgs Args);
@@ -170,7 +169,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <summary>
/// How long a Connected driver may go without a single successful read — while also reporting
/// itself non-Healthy — before the actor declares comms lost (Gitea #527). Evaluated on the
/// itself non-Healthy — before the actor declares comms lost. Evaluated on the
/// existing <see cref="HealthPollInterval"/> tick, so the effective detection granularity is
/// 30 s and the worst-case detection latency is this value plus one tick.
/// </summary>
@@ -178,8 +177,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// 90 s = three health-poll ticks. Long enough that a device answering slowly under load is not
/// torn down, short enough that an operator watching a dead PLC sees it inside two minutes.
/// Hardcoded rather than exposed in appsettings, matching <see cref="HealthPollInterval"/> and
/// <see cref="DefaultReconnectInterval"/>. Unlike the periodic drift-detector removed by Gitea
/// #523, this generates <b>no</b> outbound traffic on a healthy system: the watchdog is a local
/// <see cref="DefaultReconnectInterval"/>. Unlike the periodic drift-detector removed earlier,
/// this generates <b>no</b> outbound traffic on a healthy system: the watchdog is a local
/// read of <see cref="IDriver.GetHealth"/>, and it only reaches the network once a driver has
/// already stopped reading successfully.
/// </remarks>
@@ -202,7 +201,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private readonly TimeSpan _healthPollInterval;
/// <summary>Comms-loss watchdog threshold (#527); <see cref="TimeSpan.Zero"/> or negative disables it.</summary>
/// <summary>Comms-loss watchdog threshold; <see cref="TimeSpan.Zero"/> or negative disables it.</summary>
private readonly TimeSpan _commsLossTimeout;
/// <summary>When the actor last entered <c>Connected</c>. The comms-loss watchdog's baseline for a
@@ -274,14 +273,14 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// newly-added alarm for the life of the connection. Empty whenever no handle is held.</para></summary>
private IReadOnlyList<string> _subscribedAlarmRefs = Array.Empty<string>();
/// <summary>#662 — consecutive <see cref="HandleSubscribeAlarmsAsync"/> failures; reset on success and on
/// <summary>Consecutive <see cref="HandleSubscribeAlarmsAsync"/> failures; reset on success and on
/// <see cref="DetachAlarmSource"/> (a new connection starts a new streak).</summary>
private int _alarmSubscribeFailures;
/// <summary>#662 — health-poll ticks the alarm reconcile still skips before its next retry (backoff).</summary>
/// <summary>Health-poll ticks the alarm reconcile still skips before its next retry (backoff).</summary>
private int _alarmRetrySkipTicks;
/// <summary>#662 — backoff cap: at the production 30 s tick a failing alarm subscribe is retried at least
/// <summary>Backoff cap: at the production 30 s tick a failing alarm subscribe is retried at least
/// every 4 minutes.</summary>
private const int MaxAlarmRetrySkipTicks = 7;
@@ -305,7 +304,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <param name="healthPollInterval">Optional period of the health-poll heartbeat, which also drives the
/// subscription reconcile (<see cref="ReconcileSubscription"/>); defaults to
/// <see cref="HealthPollInterval"/>. Exists so a test can drive the reconcile without waiting 30 s.</param>
/// <param name="commsLossTimeout">Optional comms-loss watchdog threshold (#527); defaults to
/// <param name="commsLossTimeout">Optional comms-loss watchdog threshold; defaults to
/// <see cref="DefaultCommsLossTimeout"/>. <see cref="TimeSpan.Zero"/> disables the watchdog — used by
/// tests that need a Connected driver to stay Connected while reporting non-Healthy.</param>
/// <returns>A <see cref="Akka.Actor.Props"/> instance configured to create the wrapped <see cref="DriverInstanceActor"/>.</returns>
@@ -343,7 +342,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
{
var isWindowsOnly = driverType is "Galaxy";
if (!OperatingSystem.IsWindows() && isWindowsOnly) return true;
// R3-04 (theme 4 guard): GossipedRolesHave, not a bare "dev" literal Contains — the same
// GossipedRolesHave, not a bare "dev" literal Contains — the same
// case-insensitivity the rest of the role authority gives every other consumer.
if (RoleParser.GossipedRolesHave(roles, RoleParser.Dev) && isWindowsOnly) return true;
return false;
@@ -361,7 +360,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// defaults to <see cref="NullDriverCapabilityInvoker"/> (pass-through) when null.</param>
/// <param name="healthPollInterval">Period of the health-poll heartbeat, which also drives the
/// subscription reconcile; defaults to <see cref="HealthPollInterval"/> when null.</param>
/// <param name="commsLossTimeout">Comms-loss watchdog threshold (#527); defaults to
/// <param name="commsLossTimeout">Comms-loss watchdog threshold; defaults to
/// <see cref="DefaultCommsLossTimeout"/> when null, and is disabled when zero or negative.</param>
public DriverInstanceActor(
IDriver driver,
@@ -411,14 +410,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
Timers.StartPeriodicTimer("health-poll", HealthPollTick.Instance, _healthPollInterval);
}
// Ask the host to re-provision this incarnation - see ReprovisionRequested for why a supervision
// restart otherwise leaves a dead child. base.PostRestart runs first because it runs PreStart, which
// re-attaches the rediscovery / host-status sources and restarts the health timer; the reprovision
// is the part PreStart cannot do, since only the host knows this driver's config and desired set.
/// <inheritdoc />
/// <remarks>
/// Ask the host to re-provision this incarnation — see <see cref="ReprovisionRequested"/> for why a
/// supervision restart otherwise leaves a dead child. <c>base.PostRestart</c> runs first because it
/// runs <see cref="PreStart"/>, which re-attaches the rediscovery / host-status sources and restarts
/// the health timer; the reprovision is the part <see cref="PreStart"/> cannot do, since only the
/// host knows this driver's config and desired set.
/// </remarks>
protected override void PostRestart(Exception reason)
{
base.PostRestart(reason);
@@ -500,17 +496,17 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private void Connected()
{
// #477 — announce connectivity to the host so it can clear any comms-lost Quality annotation on this
// Announce connectivity to the host so it can clear any comms-lost Quality annotation on this
// driver's native alarm conditions (Bad → Good). Fire-and-forget; the host defaults conditions to a
// non-Good "waiting for initial data" quality at materialise, and this is what confirms them Good.
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true));
// #527 — baseline for the comms-loss watchdog. Re-stamped on every Connected entry so a driver that
// Baseline for the comms-loss watchdog. Re-stamped on every Connected entry so a driver that
// reconnects but never manages a read is measured from THIS connect, not from a stale earlier one.
_connectedSinceUtc = DateTime.UtcNow;
Receive<DisconnectObserved>(msg => HandleDisconnectObserved(msg.Reason));
// #676 — the driver KNOWS its connection is gone (e.g. OpcUaClient: the upstream server halted or forgot the
// The driver KNOWS its connection is gone (e.g. OpcUaClient: the upstream server halted or forgot the
// session). Same handling as the watchdog's disconnect, minus the ~90 s of silence it would need to prove it.
// Handled inline rather than re-told as DisconnectObserved (Reconnecting also swallows a stray DisconnectObserved).
Receive<ConnectionLossRaised>(msg => HandleDisconnectObserved($"driver reported connection lost: {msg.Args.Reason}"));
@@ -571,7 +567,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
/// <summary>
/// Gitea #527 — the comms-loss watchdog. Declares a Connected driver disconnected once it has gone
/// The comms-loss watchdog. Declares a Connected driver disconnected once it has gone
/// <see cref="_commsLossTimeout"/> without a single successful read <b>while also</b> reporting
/// itself non-Healthy, by self-sending <see cref="DisconnectObserved"/>.
/// </summary>
@@ -582,9 +578,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// Reconnect, so a driver that connected successfully and then lost its device stayed Connected
/// forever: it published Bad for every tag, never re-initialised, and did not recover when the device
/// came back — live-confirmed against a stopped Modbus fixture, which needed a node restart. Both
/// comms-loss quality paths (#477 native conditions, #481 scripted-alarm inputs) hang off
/// comms-loss quality paths (native conditions, scripted-alarm inputs) hang off
/// <see cref="ConnectivityChanged"/>, so both were wired to a signal that never fired.
/// Since Gitea #670 this is also <c>OpcUaClientDriver</c>'s only recovery path for a lost upstream
/// This is also <c>OpcUaClientDriver</c>'s only recovery path for a lost upstream
/// session (its in-driver SDK reconnect handler was deleted).
/// </para>
/// <para>
@@ -634,7 +630,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// Measure silence from the LATER of the last successful read and THIS connect — the grace is per
// connection. `??` was wrong: drivers PRESERVE LastSuccessfulRead across Degraded/Faulted writes (that
// preservation is the #527 design), so after a trip + reconnect to a device that accepts the connection
// preservation is the watchdog design), so after a trip + reconnect to a device that accepts the connection
// but still serves no data, the stamp is already older than the threshold and the FIRST tick of the new
// connection re-trips — churn at health-tick cadence instead of the designed grace. `??` only ever helped
// a driver that had never read at all.
@@ -653,7 +649,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
/// <summary>
/// Periodic desired-vs-actual subscription reconcile (#488), riding the existing <c>health-poll</c>
/// Periodic desired-vs-actual subscription reconcile, riding the existing <c>health-poll</c>
/// tick. While Connected, a driver that has a desired subscription set but no live handle is
/// re-subscribed.
/// </summary>
@@ -701,7 +697,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
/// <summary>
/// #662 — the native-alarm half of <see cref="ReconcileSubscription"/>. The data reconcile above never
/// The native-alarm half of <see cref="ReconcileSubscription"/>. The data reconcile above never
/// looked at alarms, so an alarm subscribe that failed on (re)connect — e.g. a session not yet ready
/// after an outage — left the feed gated for the life of the connection, with the driver Healthy and
/// its data streaming. Re-asserts both halves the feed needs: the <c>OnAlarmEvent</c> handler
@@ -718,7 +714,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
if (_driver is not IAlarmSource || _desiredAlarmRefs.Count == 0) return;
if (_alarmEventHandler is null)
{
// Unreachable while every Connected entry attaches — so if this ever logs, something regressed #662.
// Unreachable while every Connected entry attaches — so if this ever logs, something regressed.
_log.Warning("DriverInstance {Id}: connected with desired alarm refs but no native-alarm handler — re-attaching (periodic reconcile)",
_driverInstanceId);
AttachAlarmSource();
@@ -739,11 +735,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private void Reconnecting()
{
// #477 — announce comms loss to the host so it annotates this driver's native alarm conditions Bad
// Announce comms loss to the host so it annotates this driver's native alarm conditions Bad
// (a comms-lost driver emits no alarm events, so this is the ONLY signal that the source is unreachable).
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false));
// #527 — tear the dead transport down before re-initialising, or every retry leaks one.
// Tear the dead transport down before re-initialising, or every retry leaks one.
Receive<RetryConnect>(_ => InitializeAsync(_currentConfigJson ?? "{}", teardownFirst: true));
// Fast-fail writes while reconnecting (same reason as Connecting — avoids the 8s host Ask
// timeout on an inbound write to a transiently-down driver). Synchronous Receive.
@@ -799,7 +795,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <param name="teardownFirst">
/// When true, <see cref="IDriver.ShutdownAsync"/> is awaited before <see cref="IDriver.InitializeAsync"/>
/// — the sequence every driver's own <c>ReinitializeAsync</c> uses. Set on the <c>Reconnecting</c>
/// retry path (#527), because several drivers <em>overwrite</em> their transport field in
/// retry path, because several drivers <em>overwrite</em> their transport field in
/// <c>InitializeAsync</c> without disposing the previous one: <c>ModbusDriver</c> assigns
/// <c>_transport = _transportFactory(...)</c> and <c>MqttDriver</c> assigns <c>_connection</c>, both
/// over an <see cref="IAsyncDisposable"/>. Re-initialising without tearing down therefore leaks one
@@ -836,7 +832,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
"initialising anyway", driverInstanceId);
}
}
// R2-10 T10: the connect path was the ONE capability call the invoker never saw, so a
// The connect path was the ONE capability call the invoker never saw, so a
// driver that could not connect contributed zero breaker input and the resilience panel
// stayed quiet for a dead endpoint. Keyed on the driver-instance id (init spans the
// whole driver, like a bulk subscribe). The Initialize policy never retries — this
@@ -1045,7 +1041,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// Called on PostStop and on Connected → Reconnecting transitions so a stale handler doesn't push
/// data-change / alarm events to an actor that has lost its driver connection.
/// <para>Not for the data Unsubscribe / re-subscribe path — that uses <see cref="DetachDataSubscription"/>
/// (#662).</para></summary>
/// instead.</para></summary>
private void DetachSubscription()
{
DetachDataSubscription();
@@ -1054,7 +1050,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <summary>Tear down the data-change (per-tag AND batch) handlers + null the data handle, leaving the
/// native-alarm handler and handle alone.
/// <para>#662: the data Unsubscribe / re-subscribe path used to run the full <see cref="DetachSubscription"/>,
/// <para>The data Unsubscribe / re-subscribe path used to run the full <see cref="DetachSubscription"/>,
/// so every deploy that re-subscribed a Connected driver's DATA also unhooked <c>OnAlarmEvent</c> and
/// forgot the alarm handle — the alarm subscription still logged "established" but its events reached
/// nobody until a reconnect or respawn. The two subscriptions are independent at the driver; only a lost
@@ -1111,7 +1107,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
/// <summary>
/// Subscribe the driver's <see cref="IDriverConnectionLossSource.ConnectionLost"/> (#676), if it is one,
/// Subscribe the driver's <see cref="IDriverConnectionLossSource.ConnectionLost"/>, if it is one,
/// marshalling each raise to the actor thread — actor state is never touched on the driver's thread. Attached
/// once in <c>PreStart</c> and detached in <c>PostStop</c>, like <see cref="AttachRediscoverySource"/>: the
/// <see cref="IDriver"/> instance can outlive this actor, so a per-connect attach would leak a handler (holding
@@ -1134,7 +1130,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
/// <summary>
/// A connection loss reported while NOT Connected (#676): a (re)initialise is already pending or running, so
/// A connection loss reported while NOT Connected: a (re)initialise is already pending or running, so
/// there is nothing to tear down — and acting on it could tear down the connection that attempt is building.
/// </summary>
private void IgnoreConnectionLoss(ConnectionLossRaised msg) =>
@@ -1142,8 +1138,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
_driverInstanceId, msg.Args.Reason);
/// <summary>
/// Connected → Reconnecting on an observed disconnect — from the #527 watchdog or a driver's definitive
/// <see cref="IDriverConnectionLossSource.ConnectionLost"/> (#676).
/// Connected → Reconnecting on an observed disconnect — from the watchdog or a driver's definitive
/// <see cref="IDriverConnectionLossSource.ConnectionLost"/>.
/// </summary>
private void HandleDisconnectObserved(string reason)
{
@@ -1218,7 +1214,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
/// <summary>Bounded driver diagnostics, or null when the driver is not an <see cref="IDriverDiagnostics"/>
/// (Gitea #640). Pulled fresh and called UNGUARDED for the same reasons as
/// implementation. Pulled fresh and called UNGUARDED for the same reasons as
/// <see cref="CurrentSkippedTags"/>; a throwing implementation loses only the diagnostics.</summary>
private IReadOnlyDictionary<string, string>? CurrentDiagnostics()
{
@@ -1295,7 +1291,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <summary>Calls the driver's <see cref="IAlarmSource.SubscribeAlarmsAsync"/> (bounded) to register the
/// alarm subscription that un-gates its native feed, caching the returned handle. Re-checks the guard
/// (the desired set may have cleared, or another SubscribeAlarms may have already established a handle,
/// while this was queued). Failures are logged and retried on the next Connected entry or health-poll reconcile tick (#662) — the feed
/// while this was queued). Failures are logged and retried on the next Connected entry or health-poll reconcile tick — the feed
/// stays gated until then.</summary>
private async Task HandleSubscribeAlarmsAsync(SubscribeAlarms _)
{
@@ -1381,7 +1377,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <summary>Forward a per-tag-only driver's data change to the parent for OPC UA publication, as a
/// single-item batch — so the parent sees ONE message shape whether or not the driver batches.
/// <para>The driver's status code rides through UNCHANGED (#519). This used to project it onto a
/// <para>The driver's status code rides through UNCHANGED. This used to project it onto a
/// 3-state Good/Uncertain/Bad enum here, which the node manager then re-expanded to a bare
/// <c>0x80000000</c> — so no driver's sub-code ever reached a client, and the status constants each
/// driver maintains were diagnostic in logs only.</para></summary>
@@ -1395,7 +1391,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <summary>Forward one batch-capable driver production burst to the parent as a single message.
/// <para>Every item's status code and timestamp ride through exactly as
/// <see cref="OnDataChangeForward"/> carries them for a per-tag driver (#519; timestamps come from the
/// <see cref="OnDataChangeForward"/> carries them for a per-tag driver (timestamps come from the
/// driver's snapshot, never from this actor's clock).</para></summary>
private void OnDataChangeBatchForward(DataChangeBatchForward msg)
{
@@ -1444,7 +1440,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// snapshot via <c>DriverStatusHub.JoinDriver</c> which reads the store directly.
/// </summary>
/// <returns>The health observed on this call, or null when <see cref="IDriver.GetHealth"/> threw.
/// Returned so the caller can reuse the same observation — the #527 comms-loss watchdog rides this
/// Returned so the caller can reuse the same observation — the comms-loss watchdog rides this
/// call rather than polling the driver a second time and risking a different answer.</returns>
private DriverHealth? PublishHealthSnapshot()
{
@@ -1476,7 +1472,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// dedup would swallow. Flattened to a STRING for the same reason as the host digest — the
// report holds an IReadOnlyList, which a tuple compares by reference.
//
// The diagnostics digest (Gitea #640) is the fourth instance: a diagnostic fact (S7's PDU size
// The diagnostics digest is the fourth instance: a diagnostic fact (S7's PDU size
// changing across a reconnect) moves none of the other components, so without it the publish
// that carries it is deduped away. Flattened to a STRING - the bag is a dictionary, which a
// tuple compares by reference.
@@ -4,8 +4,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
/// Pure diff between the currently-running driver children (keyed by
/// <c>DriverInstance.DriverInstanceId</c>) and the target spec list from a freshly-applied
/// deployment artifact. The DriverHostActor consumes the two lists and calls
/// spawn / stop on its child actors accordingly. There is no in-place config path: since #516 a config
/// change is a stop + respawn, and #665 deleted the unreachable in-place <c>ApplyDelta</c> seam.
/// spawn / stop on its child actors accordingly. There is no in-place config path: a config
/// change is a stop + respawn, and the former in-place <c>ApplyDelta</c> seam no longer exists.
/// </summary>
/// <param name="ToSpawn">Specs with no current child (or whose child is being replaced) — create a new actor.</param>
/// <param name="ToStop">DriverInstanceIds currently running but missing from the new artifact, or now disabled.</param>
@@ -46,9 +46,9 @@ public static class DriverSpawnPlanner
// • DriverType — factory-bound, can't be reinitialized in place.
// • ResilienceConfig — the CapabilityInvoker (and its resolved options) binds to the child
// actor at spawn time; the factory invalidates the stale cached pipelines on respawn.
// • DriverConfig — was an in-place ApplyDelta until #516. It is now a respawn.
// • DriverConfig — is a respawn (it was formerly an in-place ApplyDelta).
//
// #516: the in-place delta silently DISCARDED the edit on five drivers (Modbus, FOCAS,
// the in-place delta silently DISCARDED the edit on five drivers (Modbus, FOCAS,
// OpcUaClient, AbLegacy, Sql), whose InitializeAsync served the options captured by their
// constructor and never looked at the driverConfigJson they were handed. The deployment still
// sealed green. Those five now re-parse (belt), and this respawn is the braces: several
@@ -41,21 +41,21 @@ public sealed class NativeAlarmProjector
/// and history are decided separately: a transition always projects a snapshot, but only a transition that
/// actually CHANGED what the condition shows (or that a source reports as genuinely new) writes a row.
/// <list type="bullet">
/// <item>Gitea #647 review — a <see cref="AlarmTransitionKind.Raise"/> on a condition already projected
/// <item>A <see cref="AlarmTransitionKind.Raise"/> on a condition already projected
/// Active WITH THE SAME MESSAGE (re-review R1 — a different message is a different alarm, and un-acks) is a
/// re-statement: what a driver whose told-record died with its instance sends after a deploy respawns
/// it. The acknowledgement is KEPT and no row is written. Only <see cref="AlarmTransitionKind.Retrigger"/>
/// (or inactive → active) un-acknowledges.</item>
/// <item>Gitea #656 — <see cref="AlarmTransitionKind.ActiveAcknowledged"/> projects Active+acked in ONE
/// <item><see cref="AlarmTransitionKind.ActiveAcknowledged"/> projects Active+acked in ONE
/// update (never an Active+unacked intermediate a client could see) and writes "Activated" only when the
/// condition was not already showing that alarm active, then "Acknowledged" only when it was not acked.</item>
/// <item>Gitea #657 — <see cref="AlarmTransitionKind.InactiveUnacknowledged"/> projects inactive+unacked in ONE
/// <item><see cref="AlarmTransitionKind.InactiveUnacknowledged"/> projects inactive+unacked in ONE
/// update and writes "Activated" + "Cleared" only when the condition was acknowledged (an un-ack needs a new
/// occurrence), "Cleared" alone when it was Active+unacked, nothing when it already showed exactly that.</item>
/// <item>Gitea #656 — a <see cref="AlarmEventArgs.IsRestatement"/> event (a source re-stating upstream's
/// <item>A <see cref="AlarmEventArgs.IsRestatement"/> event (a source re-stating upstream's
/// current state: a reconnect snapshot, first sight after a respawn) writes no row when it changes nothing
/// the condition shows: a Retrigger on an Active+unacked condition with the same message AND severity,
/// a Clear on an already-inactive condition, or an Acknowledge on an already-acknowledged one (#657); and a flagged Unspecified update of an already-active
/// a Clear on an already-inactive condition, or an Acknowledge on an already-acknowledged one; and a flagged Unspecified update of an already-active
/// condition moves its message/severity (node + one condition event) with active/acked kept and no row
/// (AbCip ALMA's governing-limit change). Unflagged sources (FOCAS, MTConnect, live Galaxy transitions) are
/// unaffected — a live Retrigger is a genuine re-occurrence and keeps its row.</item>
@@ -73,9 +73,9 @@ public sealed class NativeAlarmProjector
{
var prev = _prior.TryGetValue(nodeId, out var p)
? p : (Active: false, Acked: true, Message: (string?)null, Severity: (ushort)0);
// #626: a source with a finer scale than the four buckets supplies the exact Part 9 severity.
// A source with a finer scale than the four buckets supplies the exact Part 9 severity.
var sev = e.OpcUaSeverity is { } exact ? (ushort)Math.Clamp(exact, 1, 1000) : MapSeverity(e.Severity);
// Gitea #647 re-review R1: only a statement saying the SAME thing the condition already shows is a re-statement.
// Only a statement saying the SAME thing the condition already shows is a re-statement.
// A respawned driver cannot tell "the alarm I was showing" from "a different one that appeared while I was
// down", so a different message is treated as a new statement — un-acked, with its alerts row. Comparing the
// message is conservative: any difference (a sources' messages are deterministic for an unchanged statement)
@@ -88,7 +88,7 @@ public sealed class NativeAlarmProjector
case AlarmTransitionKind.Raise when sameMessage:
(active, acked, historyKinds) = (true, prev.Acked, []);
break;
// #656: a source re-stating an Active+unacked condition that already shows exactly this (message AND
// A source re-stating an Active+unacked condition that already shows exactly this (message AND
// severity — an MTConnect Warning→Fault escalation can keep the text) changes nothing the node shows.
case AlarmTransitionKind.Retrigger when e.IsRestatement && sameMessage && !prev.Acked && prev.Severity == sev:
(active, acked, historyKinds) = (true, false, []);
@@ -102,7 +102,7 @@ public sealed class NativeAlarmProjector
? [AlarmTransitionKind.Raise, AlarmTransitionKind.Acknowledge]
: !prev.Acked ? [AlarmTransitionKind.Acknowledge] : [];
break;
// #657: the mirror of ActiveAcknowledged — inactive AND unacked in ONE update (never Raise-then-Clear, which
// The mirror of ActiveAcknowledged — inactive AND unacked in ONE update (never Raise-then-Clear, which
// showed clients the condition Active again for an instant). Rows only for what changed: an acknowledged
// condition can only have become unacked through a new occurrence ("Activated" + "Cleared"); an
// Active+unacked one just cleared; one already inactive+unacked changed nothing.
@@ -112,7 +112,7 @@ public sealed class NativeAlarmProjector
? [AlarmTransitionKind.Raise, AlarmTransitionKind.Clear]
: prev.Active ? [AlarmTransitionKind.Clear] : [];
break;
// #657: a source re-stating an acknowledgement the condition already shows (OpcUaClient's first sight of
// A source re-stating an acknowledgement the condition already shows (OpcUaClient's first sight of
// an inactive+acked condition is a flagged Clear + Acknowledge) changes nothing.
case AlarmTransitionKind.Acknowledge when e.IsRestatement && prev.Acked:
(active, acked, historyKinds) = (prev.Active, true, []);
@@ -120,7 +120,7 @@ public sealed class NativeAlarmProjector
case AlarmTransitionKind.Acknowledge:
(active, acked, historyKinds) = (prev.Active, true, [AlarmTransitionKind.Acknowledge]);
break;
// #656: a re-stated Clear of a condition that is already inactive changes nothing (Galaxy replays every
// A re-stated Clear of a condition that is already inactive changes nothing (Galaxy replays every
// Inactive snapshot entry on each reconnect).
case AlarmTransitionKind.Clear when e.IsRestatement && !prev.Active:
(active, acked, historyKinds) = (false, prev.Acked, []);
@@ -130,7 +130,7 @@ public sealed class NativeAlarmProjector
break;
// A message/severity-only update of an ALREADY-ACTIVE condition that the source flags as a re-statement
// (AbCip ALMA: the governing limit changed but no new occurrence started, e.g. HH dropped back to H).
// OpcUaClient no longer reaches it (#657: its first sight of an inactive condition is a flagged Clear +
// OpcUaClient no longer reaches it (its first sight of an inactive condition is a flagged Clear +
// Acknowledge, or an InactiveUnacknowledged — never a flagged Unspecified).
// The node's text/severity move; active/acked are kept; NO row (an "Activated" row would be false).
case AlarmTransitionKind.Unspecified when e.IsRestatement && prev.Active:
@@ -147,14 +147,14 @@ public sealed class NativeAlarmProjector
return new AlarmConditionSnapshot(
Active: active, Acknowledged: acked, Confirmed: true, Enabled: true,
Shelving: AlarmShelvingKind.Unshelved, Severity: sev, Message: e.Message,
// #626: a per-condition source quality (MTConnect Unavailable) when the driver reports one. Absent
// (every pre-#626 source) ⇒ Good, as before — driver-wide comms loss stays the host's
// out-of-band WriteAlarmQuality annotation (#477), not something the projector infers.
// A per-condition source quality (MTConnect Unavailable) when the driver reports one. Absent
// (every earlier source) ⇒ Good, as before — driver-wide comms loss stays the host's
// out-of-band WriteAlarmQuality annotation, not something the projector infers.
StatusCode: e.QualityStatusCode ?? OpcUaStatus.Good);
}
/// <summary>
/// Gitea #641 review — record a client acknowledgement the node manager applied to <paramref name="nodeId"/>
/// Record a client acknowledgement the node manager applied to <paramref name="nodeId"/>
/// and routed toward the driver. The projector otherwise never sees it, and a later Clear would project the
/// stale unacknowledged prior. An untracked condition already defaults to acknowledged.
/// </summary>
@@ -168,7 +168,7 @@ public sealed class NativeAlarmProjector
public void Clear() => _prior.Clear();
/// <summary>
/// Gitea #641 — drop the tracked state of every condition NOT in <paramref name="deployedNodeIds"/>, keeping
/// Drop the tracked state of every condition NOT in <paramref name="deployedNodeIds"/>, keeping
/// the rest. Called on every apply instead of <see cref="Clear"/>: a condition that is still deployed keeps
/// its state across the deploy (the node manager carries the node's state across a rebuild too), so the
/// next Acknowledge does not project <c>Active = false</c> onto an active alarm and the next Clear does not
@@ -27,7 +27,7 @@ public static class PrimaryGatePolicy
};
/// <summary>
/// Gitea #674 review: decide whether this node may serve an OPC UA <b>HistoryUpdate</b>. The
/// Decide whether this node may serve an OPC UA <b>HistoryUpdate</b>. The
/// <see cref="ShouldServiceAsPrimary"/> verdict, but CLOSED until this node has received its first
/// redundancy snapshot.
/// </summary>
@@ -104,7 +104,7 @@ public static class PrimaryGatePolicy
/// <summary>
/// Decide whether this node should <b>capture</b> continuous-historization values into its
/// durable outbox (Gitea #537).
/// durable outbox.
/// </summary>
/// <remarks>
/// <para>
@@ -126,10 +126,10 @@ public static class PrimaryGatePolicy
/// <para>
/// The residual cost is a capture gap across a failover, bounded by how long the newly
/// promoted node takes to see its first snapshot. That is inherent to any non-duplicating
/// design; the alternative — both nodes capturing — is what #537 was filed about.
/// design; the alternative — both nodes capturing — is the approach that was rejected.
/// </para>
/// <para>
/// Gitea #672: on a CRASH the newly promoted node may not see a snapshot until auto-down (the
/// on a CRASH the newly promoted node may not see a snapshot until auto-down (the
/// redundancy singleton died with the old Primary), so the caller excludes a Primary the cluster
/// failure detector reports unreachable from <paramref name="addressSpaceSharingPeerIsPrimary"/> —
/// shrinking the gap to the failure-detector window. This method is unchanged by that; it only
@@ -89,7 +89,7 @@ public sealed class ContinuousHistorizationOptions
/// dominant term in how fast the outbox can drain. The window bounds how many of those
/// round-trips are outstanding at once, so a large tag count cannot flood the gateway. Nothing
/// about the ack changes: the pass is still acked all-or-nothing after every group has
/// reported, and the Gitea #538 per-tag quarantine still keys on "another group wrote this
/// reported, and the per-tag quarantine still keys on "another group wrote this
/// pass".
/// </para>
/// </summary>
@@ -99,7 +99,7 @@ public sealed class ContinuousHistorizationOptions
/// Maximum un-acked outbox entries before the drop-oldest capacity policy kicks in; <c>0</c>
/// means unbounded.
/// <para>
/// Defaults to 500,000 (Gitea #538) — roughly 50 MB of FasterLog, and hours-to-days of
/// Defaults to 500,000 — roughly 50 MB of FasterLog, and hours-to-days of
/// backlog depending on tag count and update rate. It is a disk backstop for the one case
/// the per-tag quarantine cannot resolve: a historian that is unreachable or refusing
/// <em>every</em> write, where nothing proves any particular tag is at fault, so the
@@ -110,7 +110,7 @@ public sealed class ContinuousHistorizationOptions
public int Capacity { get; init; } = 500_000;
/// <summary>
/// Gitea #538: consecutive failed drain passes a single historian tag may accumulate — counted
/// consecutive failed drain passes a single historian tag may accumulate — counted
/// only across passes where <em>other</em> tags wrote successfully, so a backend outage never
/// advances it — before that tag's queued entries are discarded and the FIFO head is allowed to
/// advance. Defaults to 5; clamped to at least 1 by the recorder.
@@ -130,8 +130,8 @@ public sealed class ContinuousHistorizationOptions
public double MaxBackoffSeconds { get; init; } = 30;
/// <summary>
/// Gitea #672: when <c>true</c> (the default), a redundant node whose capture is stood down for its
/// mesh-partner Primary (Gitea #537) resumes capturing as soon as the cluster failure detector reports
/// when <c>true</c> (the default), a redundant node whose capture is stood down for its
/// mesh-partner Primary resumes capturing as soon as the cluster failure detector reports
/// that Primary <b>unreachable</b>, instead of waiting for auto-down and a fresh redundancy snapshot.
/// <para>
/// A crashed Primary otherwise leaves a capture hole of failure-detection + auto-down (~25 s on the
@@ -141,7 +141,7 @@ public sealed class ContinuousHistorizationOptions
/// detection onward, and a briefly-unreachable-but-alive Primary overlaps the standby. SqlServer and
/// QuestDB absorb a duplicate of a source-timestamped sample idempotently; a driver with no source
/// timestamp (e.g. Modbus, stamped with each node's own poll time) writes a duplicate row on every
/// backend, and the Gateway backend stores duplicates. <c>false</c> restores the pre-#672 behaviour.
/// backend, and the Gateway backend stores duplicates. <c>false</c> restores the previous behaviour.
/// Only the historization capture verdict is affected — never the alarm drain or the Primary data-plane
/// gate.
/// </para>
@@ -30,7 +30,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Historian;
/// </para>
/// <para>
/// <b>Comms loss IS historized (as an outage marker).</b> On a driver disconnect
/// <c>DriverHostActor.FanCommsLossToDependencyMux</c> (#481) fans <c>(null, BadNoCommunication)</c>
/// <c>DriverHostActor.FanCommsLossToDependencyMux</c> fans <c>(null, BadNoCommunication)</c>
/// through the mux for every value ref of the driver, so the recorder receives it like any other
/// sample (it cannot, and does not try to, tell it apart from a driver's own null + Bad publish).
/// When the backend supports <see cref="HistorianValueKind.Empty"/> it is stored as an
@@ -79,7 +79,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// <param name="Acked">Entries durably written and truncated away.</param>
/// <param name="Attempted">Entries in the peeked batch.</param>
/// <param name="Abandoned">Entries discarded because their tag is poison — see
/// <see cref="DrainOnceAsync"/> (Gitea #538). Counted within <paramref name="Attempted"/>.</param>
/// <see cref="DrainOnceAsync"/>. Counted within <paramref name="Attempted"/>.</param>
private sealed record DrainResult(bool Success, int Acked, int Attempted, int Abandoned = 0);
/// <summary>Ask the recorder for its current counters (used by the meter/health wiring).</summary>
@@ -111,7 +111,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// credit that prefix. Those entries still drain; they are simply never counted here.</param>
/// <param name="DroppedUnsupportedKind">Lifetime count of values dropped because they are not historizable
/// (arrays, references) or their kind is not one the backend supports. On a numeric-only backend this
/// includes the #481 comms-loss stamps (<c>null</c> + <c>BadNoCommunication</c> ⇒ Empty): every driver
/// includes the comms-loss stamps (<c>null</c> + <c>BadNoCommunication</c> ⇒ Empty): every driver
/// disconnect adds one per historized ref of that driver.</param>
/// <param name="OutboxDropped">Lifetime count of entries the outbox dropped on capacity overflow.</param>
/// <param name="OutboxAppendFailures">Lifetime count of FAILED BATCH APPENDS at the durable boundary —
@@ -121,9 +121,9 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// may still have left entries durably queued that drain normally — see <see cref="IngestAsync"/>.</param>
/// <param name="LastDrainSucceeded">Whether the most recent drain pass acked cleanly.</param>
/// <param name="SuppressedNotPrimary">Lifetime count of values not captured because this node is
/// the Secondary of a pair whose Primary records the same refs (Gitea #537).</param>
/// the Secondary of a pair whose Primary records the same refs.</param>
/// <param name="AbandonedEntries">Lifetime count of entries discarded because their historian tag
/// kept failing while other tags were writing successfully (Gitea #538).</param>
/// kept failing while other tags were writing successfully.</param>
/// <param name="IngestFaults">Lifetime count of values dropped because the per-value gate/coercion step
/// threw — distinct from <paramref name="DroppedUnsupportedKind"/>, which counts values the backend
/// cannot carry. Non-zero here means an ingest dependency is faulting (most
@@ -156,11 +156,11 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
private readonly TimeSpan _minBackoff;
private readonly TimeSpan _maxBackoff;
/// <summary>Gitea #537: "should this node be capturing right now?". Supplied by the Runtime wiring
/// <summary>"should this node be capturing right now?". Supplied by the Runtime wiring
/// from the redundancy role view; a null gate (tests, single-node graphs) always captures.</summary>
private readonly Func<bool> _captureGate;
/// <summary>Gitea #538: consecutive failed write passes a tag may accumulate — while OTHER tags are
/// <summary>Consecutive failed write passes a tag may accumulate — while OTHER tags are
/// writing successfully — before its queued entries are abandoned so the FIFO head can advance.</summary>
private readonly int _maxWriteAttempts;
@@ -218,10 +218,10 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// <param name="drainInterval">Steady drain cadence; also the post-success reschedule.</param>
/// <param name="minBackoff">Initial retry backoff after a failed drain.</param>
/// <param name="maxBackoff">Cap on the exponential retry backoff.</param>
/// <param name="captureGate">Gitea #537: "should this node be capturing right now?", read per
/// <param name="captureGate">"should this node be capturing right now?", read per
/// value. Null (the default) always captures — the correct posture for a single-node deployment
/// and for tests.</param>
/// <param name="maxWriteAttempts">Gitea #538: consecutive failed write passes one tag may
/// <param name="maxWriteAttempts">Consecutive failed write passes one tag may
/// accumulate, while other tags are succeeding, before its entries are abandoned.</param>
/// <param name="drainConcurrency">Max historian tags one drain pass writes concurrently (must be
/// positive; 1 is the fully sequential drain).</param>
@@ -254,9 +254,9 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// <param name="drainInterval">Steady drain cadence; also the post-success reschedule.</param>
/// <param name="minBackoff">Initial retry backoff after a failed drain.</param>
/// <param name="maxBackoff">Cap on the exponential retry backoff.</param>
/// <param name="captureGate">Gitea #537: "should this node be capturing right now?", read per
/// <param name="captureGate">"should this node be capturing right now?", read per
/// value. Null (the default) always captures.</param>
/// <param name="maxWriteAttempts">Gitea #538: consecutive failed write passes one tag may
/// <param name="maxWriteAttempts">Consecutive failed write passes one tag may
/// accumulate, while other tags are succeeding, before its entries are abandoned. Clamped to at
/// least 1.</param>
/// <param name="drainConcurrency">Max historian tags one drain pass writes concurrently. Clamped to
@@ -365,7 +365,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// </summary>
/// <remarks>
/// <para>
/// <b>The gates stay per value.</b> The ref filter, the Gitea #537 capture gate and the typed-value
/// <b>The gates stay per value.</b> The ref filter, the capture gate and the typed-value
/// coercion + kind gate are evaluated for each item in turn — the capture gate in particular is a live read
/// per value, never hoisted to once per batch, so a promotion resumes capture on the very next
/// sample (pinned by <c>The_capture_gate_is_re_read_per_value_so_promotion_resumes_capture</c>).
@@ -377,7 +377,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// <c>IngestFaults</c>, logged by category, and the loop continues with the next item. Left
/// unguarded it would escape the handler into supervision, discarding every item after it in the
/// burst AND restarting the actor — which in production discards the historized-ref set (see the
/// #491 note below).
/// note below).
/// </para>
/// <para>
/// <b>Append failure is batch-wide, and it is NOT a whole-burst loss.</b> A failed group commit
@@ -403,7 +403,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
// commit (PerEntry commit mode), so it does; a fake outbox returning ValueTask.CompletedTask
// completes synchronously, the continuation runs inline with the context still installed, and the
// bug is invisible. That is exactly how it reached production — see the yielding fake in
// ContinuousHistorizationRecorderTests. Live-caught on the docker-dev rig (Gitea #491), where the
// ContinuousHistorizationRecorderTests. Live-caught on the docker-dev rig, where the
// throw escaped the handler into supervision: the actor restarted, and because production seeds an
// EMPTY ref set (the deployed set arrives later via UpdateHistorizedRefs), the restart silently
// dropped every historized ref — so historization stopped dead after the FIRST value.
@@ -524,7 +524,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
return;
}
// Gitea #537: both nodes of a redundant pair serve the same address space and see the same mux
// Both nodes of a redundant pair serve the same address space and see the same mux
// fan-out, so an ungated recorder writes every sample TWICE (measured on the docker-dev central
// pair: the gateway's write counter advanced twice per value, and halved when one node stopped).
// The gate closes only on a node whose pair partner is the Primary and is recording the same
@@ -745,7 +745,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Shutdown cut this write short. That is a property of the PASS, not of the tag:
// swallowed as `ok = false` it becomes a Gitea #538 consecutive failure, and when a
// swallowed as `ok = false` it becomes a consecutive failure, and when a
// sibling group already wrote this pass the fold books it — so a routine node stop
// can tip a perfectly HEALTHY tag over its attempt budget and discard its queued
// samples on the way out. Rethrow so it propagates through Task.WhenAll to the
@@ -759,7 +759,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
// cannot fail the whole drain task (and, now, cannot fault the WhenAll either).
// A cancellation-SHAPED exception raised while our token is still live (a gateway's
// own internal deadline, say) lands here deliberately: it is an ordinary write
// failure, and exempting it would create a tag #538 can never quarantine.
// failure, and exempting it would create a tag the failure budget can never quarantine.
ok = false;
}
@@ -778,7 +778,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
// Fold the outcomes on the single logical drain flow — NEVER inside the parallel lambdas.
// _tagWriteFailures is actor state (kept single-flight by _draining); mutating it from N
// concurrent tasks would corrupt the Gitea #538 counters. Nothing below observes completion
// concurrent tasks would corrupt the failure counters. Nothing below observes completion
// ORDER, so the fold is deterministic whatever order the writes finished in.
var succeeded = 0;
var failedGroups = new List<(string Tag, int Count)>();
@@ -812,7 +812,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
return new DrainResult(false, 0, batch.Count);
}
// Gitea #538: at least one tag wrote, so the backend IS reachable and a tag that keeps
// At least one tag wrote, so the backend IS reachable and a tag that keeps
// failing is poison — most often one whose historian tag was never provisioned (EnsureTags
// fires only for newly-ADDED historized tags, so a renamed historianTagname is easy to hit).
// Left blocking, it pins the FIFO head forever while every HEALTHY tag in the batch is
@@ -81,33 +81,33 @@ public sealed class ServerHistorianOptions
/// cap). When a resume read stalls on such a cluster, the node manager over-fetches up to
/// <c>MaxTieClusterOverfetch + 1</c> ties at that single timestamp (a <c>start == end</c> read) and
/// pages through them; this bounds how large a single-timestamp burst the server will buffer in
/// memory before it gives up and surfaces <c>BadTooManyOperations</c> for that node (#686; was
/// memory before it gives up and surfaces <c>BadTooManyOperations</c> for that node (was
/// <c>BadHistoryOperationUnsupported</c>). It is also the tie-cluster CEILING of a reverse read walked
/// back from forward reads on a backend that cannot read newest-first (the Gateway; segments are sized from the page, #689): one timestamp holding
/// back from forward reads on a backend that cannot read newest-first (the Gateway; segments are sized from the page): one timestamp holding
/// more samples than this is refused <c>BadTooManyOperations</c>. The default (65536) comfortably covers
/// any realistic same-millisecond burst; a value below 1 is treated as 1.
/// </summary>
public int MaxTieClusterOverfetch { get; init; } = 65536;
/// <summary>
/// Gitea #691: whether HistoryRead-Raw honours <c>ReadRawModifiedDetails.ReturnBounds</c> (OPC UA Part 11 bounding
/// values). Default <c>true</c>. <c>false</c> is the kill switch back to the pre-#691 answer: the flag is ignored
/// whether HistoryRead-Raw honours <c>ReadRawModifiedDetails.ReturnBounds</c> (OPC UA Part 11 bounding
/// values). Default <c>true</c>. <c>false</c> is the kill switch back to the previous answer: the flag is ignored
/// (stored samples only) and a modified read carrying it is not refused <c>Bad_InvalidArgument</c>. Note the .NET
/// SDK's <c>new ReadRawModifiedDetails()</c> defaults <c>ReturnBounds</c> (and <c>IsReadModified</c>) to <c>true</c>.
/// </summary>
public bool HonorReturnBounds { get; init; } = true;
/// <summary>
/// Gitea #693, <c>Gateway</c> backend only: whether HistoryRead-AtTime is served from RAW gateway reads evaluated with
/// <c>Gateway</c> backend only: whether HistoryRead-AtTime is served from RAW gateway reads evaluated with
/// the SQL backends' shared AtTime rules (exact stored value at a stored time, linear between usable neighbours with
/// the Interpolated bit, held before a Bad neighbour as Uncertain, null + the outage's Bad code inside an outage,
/// <c>BadNoData</c> before the first sample). Default <c>true</c>. <c>false</c> is the kill switch back to the
/// pre-#693 answer: AVEVA's own interpolation (the gateway's <c>ReadAtTime</c>), passed through unchanged.
/// previous answer: AVEVA's own interpolation (the gateway's <c>ReadAtTime</c>), passed through unchanged.
/// </summary>
public bool GatewayAtTimeFromRaw { get; init; } = true;
/// <summary>
/// Gitea #694 (opt-in): HistoryReadEvents never reads events older than <c>now − EventReadHorizon</c> — the earlier
/// Opt-in: HistoryReadEvents never reads events older than <c>now − EventReadHorizon</c> — the earlier
/// bound of every fresh events window is raised to it (both directions, every backend; a window wholly older is
/// <c>GoodNoData</c>). Default <see cref="TimeSpan.Zero"/> = no horizon: every read is exact to its own window. It
/// exists for the Gateway, where proving "no older events" costs a read down to the Unix epoch on
@@ -145,7 +145,7 @@ public sealed class ServerHistorianOptions
public TimeSpan HistoryReadDeadline { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>
/// <c>SqlServer</c> / <c>QuestDb</c> backends only (#671): the most raw in-window samples one Part 13
/// <c>SqlServer</c> / <c>QuestDb</c> backends only: the most raw in-window samples one Part 13
/// time-weighted read (TimeAverage, TimeAverage2, Total, Total2, Interpolative) may stream into the server-side
/// evaluator — that family is not pushed down to SQL. A read past the cap stops at cap + 1 rows and fails THAT
/// node with <c>BadTooManyOperations</c> instead of holding a pooled connection until
@@ -155,7 +155,7 @@ public sealed class ServerHistorianOptions
public int MaxTimeWeightedRawRows { get; init; } = 1_000_000;
/// <summary>
/// Gitea #674: how far into the future an OPC UA HistoryUpdate (Insert / Replace / Update) item's
/// how far into the future an OPC UA HistoryUpdate (Insert / Replace / Update) item's
/// <c>SourceTimestamp</c> may lie, measured from the server clock. An item beyond <c>now + skew</c> is refused
/// <c>BadOutOfRange</c> by the node manager before any backend sees it — a far-future row is never a legitimate
/// history edit, and on a backend that judges retention against the newest timestamp it could age out every
@@ -3,7 +3,7 @@ using Microsoft.Extensions.Configuration;
namespace ZB.MOM.WW.OtOpcUa.Runtime;
/// <summary>
/// The definitions of "this node's LocalDb is replicated to a peer" (#603) — one place, two deliberately
/// The definitions of "this node's LocalDb is replicated to a peer" — one place, two deliberately
/// different predicates for the two consumers: the Host's table-registration step
/// (<c>LocalDbSetup.ReplicationIsConfigured</c> → <see cref="CapturesChanges"/>: which nodes capture
/// changes) and the alarm-historian drain gate (<c>AddAlarmHistorian</c> → <see cref="SharesRowsWithPeer"/>:
@@ -47,13 +47,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// referencing UNS node in <see cref="AddressSpaceRealm.Uns"/>) with identical value/status/timestamp.
/// <see cref="Realm"/> defaults to <see cref="AddressSpaceRealm.Uns"/> so pre-v3 callers (VirtualTag
/// equipment nodes) keep compiling; the driver fan-out passes it EXPLICITLY per node.
/// <para><see cref="StatusCode"/> is the full OPC UA status code, sub-code included (#519); the sink
/// <para><see cref="StatusCode"/> is the full OPC UA status code, sub-code included; the sink
/// hands it to the SDK verbatim.</para></summary>
public sealed record AttributeValueUpdate(string NodeId, object? Value, uint StatusCode, DateTime TimestampUtc, AddressSpaceRealm Realm);
/// <summary>Batched form of <see cref="AttributeValueUpdate"/>: every fan-out write of one driver
/// production burst in one message — the sink takes its lock once for the whole batch. Items carry
/// their realm each (<see cref="ValueWrite"/>); status codes ride verbatim (#519).</summary>
/// their realm each (<see cref="ValueWrite"/>); status codes ride verbatim.</summary>
public sealed record AttributeValueBatchUpdate(IReadOnlyList<ValueWrite> Items);
/// <summary>Status-only batch: every named node keeps its CURRENT value and only its status +
@@ -76,7 +76,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <param name="Realm">The namespace realm the condition lives in — <see cref="AddressSpaceRealm.Uns"/> for
/// scripted alarms (default), <see cref="AddressSpaceRealm.Raw"/> for v3 native raw conditions.</param>
public sealed record AlarmStateUpdate(string AlarmNodeId, AlarmConditionSnapshot State, DateTime TimestampUtc, AddressSpaceRealm Realm);
/// <summary>#477 — annotate a materialised condition's source-data Quality out of band from any alarm
/// <summary>Annotate a materialised condition's source-data Quality out of band from any alarm
/// transition (the driver-connectivity path: comms lost → <see cref="OpcUaStatus.BadNoCommunication"/>,
/// restored → <see cref="OpcUaStatus.Good"/>). Routed to <see cref="IOpcUaAddressSpaceSink.WriteAlarmQuality"/>,
/// which sets ONLY Quality and fires one Part 9 event on a status-code change.</summary>
@@ -101,7 +101,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// on the normal path, where loading from the ConfigDb by id is correct.
/// </param>
/// <param name="ReportOutcome">
/// Gitea #601 — when <see langword="true"/>, the actor replies to the sender with a
/// when <see langword="true"/>, the actor replies to the sender with a
/// <see cref="RebuildCompleted"/> once the apply outcome is known (clean or degraded), on EVERY path
/// through the handler. <c>DriverHostActor</c> sets it on the deploy path and sends the deployment's
/// ack only after that reply, so a degraded apply can no longer seal a deployment green. Off for the
@@ -112,7 +112,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
bool ReportOutcome = false);
/// <summary>
/// Gitea #601 — the reply to a <see cref="RebuildAddressSpace"/> carrying
/// the reply to a <see cref="RebuildAddressSpace"/> carrying
/// <see cref="RebuildAddressSpace.ReportOutcome"/>: whether the address-space apply was clean.
/// </summary>
/// <param name="Correlation">The rebuild's correlation id, echoed.</param>
@@ -134,7 +134,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private readonly NodeId? _localNode;
private readonly IDbContextFactory<OtOpcUaConfigDbContext>? _dbFactory;
private readonly AddressSpaceApplier? _applier;
/// <summary>#520 stage 4 — receives the API keys + ACL grants carried by each applied artifact, so
/// <summary>Receives the API keys + ACL grants carried by each applied artifact, so
/// OPC UA session activation can authenticate. Null when nothing consumes it (tests, and any node
/// that is not serving an OPC UA data plane).</summary>
private readonly IDataPlaneAuthoritySink? _dataPlaneAuthority;
@@ -155,11 +155,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private byte _lastServiceLevel;
private bool _publishedAtLeastOnce;
/// <summary>True once a real composition has been applied, i.e. there is a served address space worth
/// protecting. Distinguishes "the artifact went missing under a running server" (issue #485 — warn, and
/// protecting. Distinguishes "the artifact went missing under a running server" (warn, and
/// hold what is materialised) from "nothing has been deployed here yet" (a quiet no-op at boot).</summary>
private bool _hasAppliedComposition;
/// <summary>
/// Gitea #601 review — <see cref="_lastApplied"/> was advanced by a DEGRADED rebuild (a rebuild advances
/// <see cref="_lastApplied"/> was advanced by a DEGRADED rebuild (a rebuild advances
/// even with swallowed failures, see <see cref="HandleRebuildCore"/>). A re-deploy of the same revision
/// then diffs to an EMPTY plan; without this flag that empty plan reported clean, so the "re-deploy
/// re-applies" repair path sealed green over an address space still known to be partial. While set, an
@@ -208,6 +208,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <param name="dbLess">Per-cluster mesh Phase 4: this is a driver-only node with no ConfigDb, so the
/// ServiceLevel DB-reachability input is retired (<c>DbReachable</c> treated constant-true, only
/// staleness demotes). No <paramref name="dbHealthProbe"/> is wired on such a node.</param>
/// <param name="dataPlaneAuthority">The optional sink that receives the API keys and ACL grants carried by each applied artifact.</param>
/// <returns>The configured <see cref="Props"/> for creating this actor, pinned to the
/// <see cref="DispatcherId"/> dispatcher.</returns>
public static Props Props(
@@ -260,6 +261,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <param name="dbLess">Per-cluster mesh Phase 4: this is a driver-only node with no ConfigDb, so the
/// ServiceLevel DB-reachability input is retired (<c>DbReachable</c> treated constant-true, only
/// staleness demotes). No <paramref name="dbHealthProbe"/> is wired on such a node.</param>
/// <param name="dataPlaneAuthority">The optional sink that receives the API keys and ACL grants carried by each applied artifact.</param>
/// <returns>The configured <see cref="Props"/> for creating this actor in tests, without dispatcher
/// pinning or the DPS subscribe.</returns>
public static Props PropsForTests(
@@ -312,6 +314,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <param name="dbLess">Per-cluster mesh Phase 4: this is a driver-only node with no ConfigDb, so the
/// ServiceLevel DB-reachability input is retired (<c>DbReachable</c> treated constant-true, only
/// staleness demotes). No <paramref name="dbHealthProbe"/> is wired on such a node.</param>
/// <param name="dataPlaneAuthority">The optional sink that receives the API keys and ACL grants carried by each applied artifact.</param>
public OpcUaPublishActor(
IOpcUaAddressSpaceSink sink,
IServiceLevelPublisher serviceLevel,
@@ -489,7 +492,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
finally
{
// Gitea #641 — close the apply on EVERY exit, early returns and a throwing pass included: the node
// close the apply on EVERY exit, early returns and a throwing pass included: the node
// manager reports here the native conditions a rebuild carried over (after the notifier wiring the
// passes did) and discards any captured state no materialise claimed. Skipping it on a throw would
// leave that state for a later surgical re-add of the same id to resurrect. No-op when nothing is
@@ -501,12 +504,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
}
// Gitea #601 — the outcome goes out only after the apply (including #641's completion step) is done.
// the outcome goes out only after the apply (including its completion step) is done.
if (msg.ReportOutcome)
requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason));
}
/// <summary>The rebuild pipeline. Returns whether the apply was degraded, and why (Gitea #601).</summary>
/// <summary>The rebuild pipeline. Returns whether the apply was degraded, and why.</summary>
private (bool Degraded, string? Reason) HandleRebuildCore(RebuildAddressSpace msg)
{
using var span = OtOpcUaTelemetry.StartAddressSpaceRebuildSpan();
@@ -546,14 +549,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
// Sealed, so LoadLatestArtifact would return the PREVIOUS revision and materialise a stale
// composition (variables that don't match the SubscribeBulk refs); fall back to latest-sealed
// only for legacy callers that carry neither. With NO bytes AND no ConfigDb there is nothing
// to load, so yield Array.Empty<byte>() — the #485 guard below reads that as "no answer" and
// to load, so yield Array.Empty<byte>() — the guard below reads that as "no answer" and
// abandons the rebuild, holding last-known-good rather than wiping the address space.
var artifact = msg.Artifact
?? (_dbFactory is not null
? (msg.DeploymentId is { } depId ? LoadArtifact(depId) : LoadLatestArtifact())
: Array.Empty<byte>());
// Issue #485 — an artifact we could not obtain is NOT an empty configuration. Parsing zero
// An artifact we could not obtain is NOT an empty configuration. Parsing zero
// bytes yields an empty composition, which the planner diffs against the live one as a
// PureRemove and the applier then faithfully tears down: a transient ConfigDb blip empties the
// served address space. Nothing legitimate produces a zero-length blob (an operator who really
@@ -582,11 +585,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
// EMPTY result — and an empty composition is not a benign no-op here: the planner diffs it as a
// PureRemove and the applier tears the served address space down. So the throw is the honest
// outcome, and it lands in this method's catch below: logged at Error, _lastApplied untouched,
// last-known-good still served. Same "no answer ≠ empty configuration" rule as the #485 guard
// last-known-good still served. Same "no answer ≠ empty configuration" rule as the guard
// immediately above, applied to bytes that arrived unreadable rather than absent.
using var parsed = DeploymentArtifact.Open(artifact);
// #520 stage 4 — install this artifact's API keys + ACL grants BEFORE the address-space work
// install this artifact's API keys + ACL grants BEFORE the address-space work
// below, and deliberately ahead of the `plan.IsEmpty` early-return: an artifact that revokes a
// key or edits a grant without touching a single node produces an EMPTY address-space plan, so
// feeding this after that return would leave a revoked key authenticating until some unrelated
@@ -604,7 +607,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
{
if (_lastAppliedDegraded)
{
// #601 review — the composition is unchanged but the last apply of it was a degraded
// The composition is unchanged but the last apply of it was a degraded
// rebuild: re-ensure every node (each Ensure* no-ops on a node that stands) so the
// re-deploy actually repairs what that rebuild could not place.
var repairFailed = _applier.MaterialiseHierarchy(composition)
@@ -669,7 +672,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
{
_lastApplied = composition;
_hasAppliedComposition = true;
// #601 review — advanced despite failures only on a rebuild; remember it so an identical
// Advanced despite failures only on a rebuild; remember it so an identical
// re-deploy repairs instead of short-circuiting clean on the empty plan.
_lastAppliedDegraded = outcome.RebuildFailed || failedNodes > 0;
}
@@ -680,7 +683,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
msg.Correlation, failedNodes);
}
// R2-07 T4b — on a NON-rebuild apply (PureAdd / AttributeOnly), the Materialise passes above
// On a NON-rebuild apply (PureAdd / AttributeOnly), the Materialise passes above
// just created exactly the added nodes WITHOUT tearing anything down, so announce them with a
// Part 3 GeneralModelChangeEvent(NodeAdded) per affected parent — model-aware clients then
// re-browse and pick up the new nodes while every existing MonitoredItem stays alive. Ordering
@@ -689,7 +692,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
// (subscriptions are dead anyway) — the guard skips it. AnnounceAddedNodes is Safe-wrapped
// internally, so a faulting announce can never break the deploy.
//
// The announce is realm-aware (Gitea #599): UNS parents in the Uns realm, and the parents of
// The announce is realm-aware: UNS parents in the Uns realm, and the parents of
// added RAW containers/tags in the Raw realm. It matters because of the delta work — before it, a
// plan carrying raw adds went through a full RebuildAddressSpace, so every client re-browsed
// anyway; now those adds are materialised surgically while existing subscriptions stay alive, and
@@ -724,7 +727,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <summary>
/// Run the five node-materialising applier passes — Raw subtree, UNS references, scripted alarms,
/// equipment tags, equipment VirtualTags — either over the FULL composition (after a rebuild) or over
/// just this plan's delta (surgical-deploys Task 6). <c>MaterialiseHierarchy</c> is NOT one of them:
/// just this plan's delta (surgical deploys). <c>MaterialiseHierarchy</c> is NOT one of them:
/// the caller always runs it in full, because parents must exist before any add.
/// </summary>
/// <remarks>
@@ -869,7 +872,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <summary>
/// Decode the artifact's data-plane authorization inputs (API keys + this cluster's ACL grants)
/// and install them for OPC UA session activation (#520 stage 4). No-op when nothing consumes
/// and install them for OPC UA session activation. No-op when nothing consumes
/// them.
/// </summary>
/// <remarks>
@@ -902,7 +905,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
snapshot.GenerationId, projection.ClusterId ?? "(single-cluster)", revision[..12],
projection.Keys.Count, projection.Grants.Count, projection.ScopePaths.Count);
// Reported BY the trie build (#520 stage 5), not re-derived here. The previous version of this
// Reported BY the trie build, not re-derived here. The previous version of this
// log counted unresolvable ScopeIds itself and so agreed with the builder on exactly one of its
// four drop reasons — a row with a blank ScopeId, a retired scope kind, or a scope path that
// does not start at a realm all vanished with the log still reading zero. A dropped row is an
@@ -935,7 +938,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <summary>Read a specific deployment's artifact blob from ConfigDb (the one just applied,
/// which may not be Sealed yet). Empty array on any failure — <see cref="HandleRebuild"/> treats that as
/// "no answer" and abandons the rebuild, leaving the served address space untouched (issue #485).</summary>
/// "no answer" and abandons the rebuild, leaving the served address space untouched.</summary>
private byte[] LoadArtifact(DeploymentId deploymentId)
{
try
@@ -41,7 +41,7 @@ public interface IRedundancyRoleView
}
/// <summary>
/// A singleton snapshot of the continuous-historization <b>capture</b> decision (Gitea #537), so
/// A singleton snapshot of the continuous-historization <b>capture</b> decision, so
/// the recorder can ask "should this node be recording historized values right now?".
/// </summary>
/// <remarks>
@@ -52,7 +52,7 @@ public interface IRedundancyRoleView
/// where the alarm section is enabled, while this one is registered unconditionally on every
/// driver-role node. Piggybacking on the alarm registration would silently drop the
/// historization gate on any pair that runs historization without alarm history — the same
/// registration accident Gitea #511 documents on the neighbouring verdict.
/// registration accident documented on the neighbouring verdict.
/// </para>
/// <para>
/// Publishes the <i>decision</i> rather than the role, so
@@ -76,7 +76,7 @@ public interface IHistorizationRoleView
}
/// <summary>
/// Gitea #674 review: a singleton snapshot of the OPC UA <b>HistoryUpdate</b> verdict
/// a singleton snapshot of the OPC UA <b>HistoryUpdate</b> verdict
/// (<see cref="PrimaryGatePolicy.ShouldServeHistoryUpdate"/>), read by the node manager's HistoryUpdate Primary gate.
/// </summary>
/// <remarks>
@@ -113,7 +113,7 @@ public interface IHistoryUpdateRoleView
public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRoleSource, IHistorizationRoleView,
IHistoryUpdateRoleView
{
// Gitea #674 review: seeded CLOSED, unlike the data-plane verdict. HistoryUpdate waits for a real redundancy verdict
// seeded CLOSED, unlike the data-plane verdict. HistoryUpdate waits for a real redundancy verdict
// (PrimaryGatePolicy.ShouldServeHistoryUpdate); a node that never publishes here is not a driver node with a
// redundancy manager, and such a node does not register this view as its gate source.
private volatile bool _shouldServeHistoryUpdate =
@@ -30,7 +30,7 @@ public sealed class DependencyMuxTagUpstreamSource : ITagUpstreamSource
// The status an "unknown path" snapshot carries — a path nothing has ever pushed to.
//
// This is deliberately BadWaitingForInitialData rather than the bare Bad (0x80000000u) it used
// to be, and the distinction is load-bearing (#481, closing #478 Finding 3). Both codes are Bad,
// to be, and the distinction is load-bearing. Both codes are Bad,
// so the engine's AreInputsReady gate treats them identically and the cold-start hold is
// unchanged. What changed is that "no data has ever arrived" is now tellable apart from "a
// driver pushed Bad", which previously looked identical whenever the pushed Bad carried a null
@@ -20,7 +20,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
/// The LocalDb replacement for <c>EfAlarmConditionStateStore</c> (which persisted to the
/// central config DB's <c>ScriptedAlarmState</c> table). Per-cluster mesh Phase 4 cuts the
/// ConfigDb from driver-only nodes, so this state moves into the same replicated LocalDb
/// file the Phase-2 alarm store-and-forward buffer already lives in — a node's condition
/// file the alarm store-and-forward buffer already lives in — a node's condition
/// state then mirrors to its redundant pair peer instead of depending on central SQL.
/// </para>
/// <para>
@@ -301,7 +301,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
}
/// <summary>
/// #487 — re-project every loaded alarm that is NOT in the Part 9 "no-event" position back onto
/// re-project every loaded alarm that is NOT in the Part 9 "no-event" position back onto
/// its condition node, right after a (re)load.
///
/// <para>
@@ -322,7 +322,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// telemetry hub. That is the whole reason it reads <see cref="ScriptedAlarmEngine.GetProjections"/>
/// (a plain read returning <see cref="ScriptedAlarmProjection"/>) rather than re-emitting: an
/// <c>alerts</c> row per alarm per deploy would append a duplicate historian / AVEVA record
/// every time anyone deploys — the alarm analogue of the VirtualTag M1 historian issue.
/// every time anyone deploys — the alarm analogue of the VirtualTag historian issue.
/// </para>
///
/// <para>
@@ -393,10 +393,10 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
private void OnDependencyChanged(VirtualTagActor.DependencyValueChanged msg)
{
// Feed the live value into the upstream the engine subscribes from. #478 — carry the source
// Feed the live value into the upstream the engine subscribes from. Carry the source
// driver's quality (mapped to an OPC UA StatusCode) so the engine can derive a scripted
// condition's worst-of-input quality; a Bad/Uncertain input is no longer silently treated as Good.
// #519 — the status code rides through verbatim. This used to convert the incoming value onto a
// the status code rides through verbatim. This used to convert the incoming value onto a
// 3-state enum and straight back again through a pair of mutually-inverse mappers, which is where
// the input's sub-code was lost before the engine ever cached it.
_upstream.Push(msg.TagId,
@@ -439,11 +439,11 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
return;
}
// #478 — QualityChanged is a source-quality annotation (worst-of-input bucket moved with no Part 9
// QualityChanged is a source-quality annotation (worst-of-input bucket moved with no Part 9
// state transition — e.g. an input went Bad, freezing the condition). Route it to the dedicated
// WriteAlarmQuality node path (sets ONLY Quality, one Part 9 event on a bucket change): NO full-state
// projection (would clobber severity/message) and NO /alerts row (it is not a state transition, so it
// must not historize). Same out-of-band quality path native comms-loss uses (#477 Layer 2).
// must not historize). Same out-of-band quality path native comms-loss uses.
if (e.Emission == EmissionKind.QualityChanged)
{
_publishActor.Tell(new OpcUaPublishActor.AlarmQualityUpdate(
@@ -517,7 +517,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
if (_driverMemberCountProvider is not null) return _driverMemberCountProvider();
try
{
// R3-04 (01/C-9): GossipedRolesHave, not ordinal Contains — a peer gossiping a miscased
// GossipedRolesHave, not ordinal Contains — a peer gossiping a miscased
// 'Driver' (rolling-upgrade window) must still count toward the alerts-emit gate.
return Akka.Cluster.Cluster.Get(Context.System).State.Members
.Count(m => m.Status == Akka.Cluster.MemberStatus.Up
@@ -711,7 +711,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
private static AlarmConditionSnapshot ToSnapshot(ScriptedAlarmEvent e)
=> ToSnapshot(e.Condition, e.Severity, e.Message, e.WorstInputStatusCode);
/// <summary>#487 — the same projection for a <see cref="ScriptedAlarmProjection"/>: a state READ used
/// <summary>The same projection for a <see cref="ScriptedAlarmProjection"/>: a state READ used
/// to restore a condition node after a rebuild, never an emission. Shares
/// <see cref="ToSnapshot(AlarmConditionState, AlarmSeverity, string, uint)"/> with the transition path
/// so a re-asserted node is byte-identical to what the alarm's own transition would have written.</summary>
@@ -736,11 +736,11 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
Shelving: MapShelving(condition.Shelving.Kind),
Severity: (ushort)SeverityToInt(severity),
Message: message,
// #478 — the condition's status is the worst status across the script's input tags at evaluation
// the condition's status is the worst status across the script's input tags at evaluation
// time (carried on the event by the engine). A transition fired while an input is Uncertain projects
// Uncertain here so the full-snapshot write doesn't clobber quality back to Good.
StatusCode: worstInputStatusCode,
// Gitea #597 — the engine's own expiry, so the node's UnshelveTime counts down to it.
// the engine's own expiry, so the node's UnshelveTime counts down to it.
UnshelveAtUtc: condition.Shelving.Kind == ShelvingKind.Timed ? condition.Shelving.UnshelveAtUtc : null);
/// <summary>Maps the Core <see cref="ShelvingKind"/> onto the Commons <see cref="AlarmShelvingKind"/>
@@ -71,11 +71,11 @@ public static class ServiceCollectionExtensions
services.TryAddSingleton<IServiceLevelPublisher>(NullServiceLevelPublisher.Instance);
services.TryAddSingleton<IDriverHealthPublisher, AkkaDriverHealthPublisher>();
// Per-cluster mesh Phase 5: the node-local live-telemetry fan-out hub. Feeds this node's OWN
// telemetry (never DPS) to the Phase-5 gRPC streaming service central dials in on. AddOtOpcUaRuntime
// telemetry (never DPS) to the gRPC streaming service central dials in on. AddOtOpcUaRuntime
// runs only inside Program.cs's hasDriver block, so this lands on driver-role nodes only.
services.TryAddSingleton<ITelemetryLocalHub, TelemetryLocalHub>();
// Gitea #511: the Primary data-plane verdict, published for drivers that assert a standing
// the Primary data-plane verdict, published for drivers that assert a standing
// exclusive identity on a shared external system (today the MQTT driver's Sparkplug host id).
//
// Registered HERE, unconditionally on every driver-role node, and NOT alongside the alarm
@@ -83,7 +83,7 @@ public static class ServiceCollectionExtensions
// enabled. Piggybacking on it would leave a redundant pair with no alarm historian configured
// with no primary-role source at all, and the driver's documented no-source fallback is
// "claim" — so both nodes of that pair would claim the same host id and their Wills would
// fight over the retained STATE. Exactly the failure #511 exists to prevent, reached by a
// fight over the retained STATE. Exactly the failure that claim gate exists to prevent, reached by a
// registration accident in an unrelated section.
//
// Both interfaces are forwarded to ONE RedundancyRoleView instance, so a node that has both
@@ -91,20 +91,20 @@ public static class ServiceCollectionExtensions
services.TryAddSingleton<RedundancyRoleView>();
services.TryAddSingleton<IDriverPrimaryRoleSource>(sp => sp.GetRequiredService<RedundancyRoleView>());
// Gitea #537: the continuous-historization capture verdict, registered here — unconditionally on
// the continuous-historization capture verdict, registered here — unconditionally on
// every driver-role node — for the same reason as the line above, and NOT alongside the alarm
// drain's IRedundancyRoleView. AddAlarmHistorian registers that one only when its own section is
// enabled, so piggybacking would leave a redundant pair that historizes values but not alarms
// with no gate at all, and both nodes would write every sample twice with nothing to say so.
services.TryAddSingleton<IHistorizationRoleView>(sp => sp.GetRequiredService<RedundancyRoleView>());
// Gitea #674 review: the OPC UA HistoryUpdate verdict — the data-plane verdict, but closed until this node's first
// The OPC UA HistoryUpdate verdict — the data-plane verdict, but closed until this node's first
// redundancy snapshot. Same instance; registered here (driver-role nodes only) so an admin-only node, which has no
// redundancy manager, wires no HistoryUpdate gate at all.
services.TryAddSingleton<IHistoryUpdateRoleView>(sp => sp.GetRequiredService<RedundancyRoleView>());
// The node→central ack transport under MeshTransport:Mode = Grpc (mesh gRPC command plane,
// Task 1B.2). Registered unconditionally but resolved only by the Grpc arm of
// The node→central ack transport under MeshTransport:Mode = Grpc (mesh gRPC command plane).
// Registered unconditionally but resolved only by the Grpc arm of
// WithOtOpcUaRuntimeActors — the mode is not knowable here (this runs before configuration is
// read into options), and a singleton nobody resolves is never constructed, so a Dps node
// opens no channel.
@@ -285,7 +285,7 @@ public static class ServiceCollectionExtensions
}
/// <summary>
/// Review R6 MINOR-4 — "does this snapshot node hold my replicated alarm queue?" for a node that does not
/// "Does this snapshot node hold my replicated alarm queue?" for a node that does not
/// dial its peer. Both halves of a LocalDb pair hold the same rows, but only the dialling half knows its
/// partner (<c>LocalDb:Replication:PeerAddress</c>); the passive half (<c>ApiKey</c> + <c>SyncListenPort</c>)
/// knew nobody, so as Secondary it never stood its drain down and both nodes delivered every alarm event.
@@ -374,7 +374,7 @@ public static class ServiceCollectionExtensions
// Per-cluster mesh Phase 4: scripted-alarm condition-state store. Registered by the Host's
// AddOtOpcUaLocalDb on driver-role nodes (the replicated LocalDb store), so condition state
// persists with no ConfigDb; null elsewhere (admin-only graphs, test harnesses) → the actor
// skips spawning the alarm host (the ConfigDb-backed EF fallback was retired in Phase 4 Task 9).
// skips spawning the alarm host (the ConfigDb-backed EF fallback was retired).
var alarmStateStore = resolver.GetService<IAlarmStateStore>();
// Per-cluster mesh Phase 3: ConfigSource:Mode selects where this driver reads config.
// FetchAndCache pulls the artifact from central over gRPC and reads only the LocalDb cache;
@@ -394,7 +394,7 @@ public static class ServiceCollectionExtensions
// Host of this node's LocalDb replication partner: the ONLY node that holds a copy of this
// node's alarm queue, and so the only node it may stand down in favour of. Null when this
// node dials nobody — unpaired (never stand down), or the PASSIVE half of a pair, which is
// told its partner through BuildAlarmQueuePeerPredicate instead (review R6 MINOR-4).
// told its partner through BuildAlarmQueuePeerPredicate instead.
var replicationPeerHost =
Uri.TryCreate(
resolver.GetService<IConfiguration>()?["LocalDb:Replication:PeerAddress"],
@@ -504,7 +504,7 @@ public static class ServiceCollectionExtensions
drainInterval: TimeSpan.FromSeconds(continuousOptions.DrainIntervalSeconds),
minBackoff: TimeSpan.FromSeconds(continuousOptions.MinBackoffSeconds),
maxBackoff: TimeSpan.FromSeconds(continuousOptions.MaxBackoffSeconds),
// Gitea #537: read the verdict PER VALUE off the shared role view rather
// read the verdict PER VALUE off the shared role view rather
// than capturing a bool, so a promotion resumes capture on the next sample.
// The view is registered unconditionally on driver nodes; a null one (test
// graphs) captures unconditionally, which is the right posture there.
@@ -550,7 +550,7 @@ public static class ServiceCollectionExtensions
loggerFactory.CreateLogger<AddressSpaceApplier>(),
provisioning: provisioning,
historizedSubscriptions: historizedSubscriptions);
// #520 stage 4 — the sink that receives each applied artifact's API keys + ACL grants, so OPC
// the sink that receives each applied artifact's API keys + ACL grants, so OPC
// UA session activation can authenticate. Optional: GetService (not GetRequiredService), because
// a node with no driver role never registers it and test harnesses build this graph without it;
// the actor treats null as "nothing consumes authorization inputs" and skips the decode.
@@ -576,10 +576,10 @@ public static class ServiceCollectionExtensions
PeerProbeSupervisorName);
registry.Register<PeerProbeSupervisorKey>(peerProbes);
// Gitea #537: "does this snapshot node record the same historized refs as me?" — true only
// "does this snapshot node record the same historized refs as me?" — true only
// for a partner in this node's own per-cluster mesh, which is exactly the set that serves
// this node's address space. A node carrying NO cluster-scoped role (the legacy,
// pre-Phase-6 shape) cannot establish that, so the predicate stays null and this node never
// older shape) cannot establish that, so the predicate stays null and this node never
// stands down: on a fleet-wide election the elected Primary is usually running a DIFFERENT
// cluster's configuration, and deferring to it would silently end this cluster's
// historization altogether — the same scope mismatch that once suspended the alarm drain on
@@ -622,22 +622,22 @@ public static class ServiceCollectionExtensions
// emits its Primary-gated native-alarm transitions into it and threads it into the
// VirtualTag + ScriptedAlarm hosts it spawns.
telemetryHub: resolver.GetService<ITelemetryLocalHub>(),
// Gitea #511: where this actor publishes its Primary DATA-PLANE verdict for drivers
// where this actor publishes its Primary DATA-PLANE verdict for drivers
// that claim an exclusive external identity. Registered unconditionally by
// AddOtOpcUaRuntime, unlike redundancyRoleView above — see the comment there.
primaryRoleSource: resolver.GetService<IDriverPrimaryRoleSource>(),
// Gitea #537: where this actor publishes the continuous-historization CAPTURE
// where this actor publishes the continuous-historization CAPTURE
// verdict, and how it decides which peer is worth standing down for.
historizationRoleView: resolver.GetService<IHistorizationRoleView>(),
sharesHistorizationScopeWithLocal: historizationScopePeer,
// Gitea #672: stop deferring the capture to a recording Primary the failure detector
// stop deferring the capture to a recording Primary the failure detector
// already reports unreachable. Unbound section ⇒ the option's default (true).
captureWhilePrimaryUnreachable: continuousOptions?.CaptureWhilePrimaryUnreachable ?? true,
// Review R6 MINOR-4: the passive half of a LocalDb pair has no PeerAddress, so it is told
// The passive half of a LocalDb pair has no PeerAddress, so it is told
// its queue-sharing peer as its mesh partner instead — otherwise it never stands down.
sharesAlarmQueueWithLocal: BuildAlarmQueuePeerPredicate(
resolver.GetService<IConfiguration>(), roleInfo, replicationPeerHost),
// Gitea #674 review: the HistoryUpdate verdict (closed until the first redundancy snapshot).
// The HistoryUpdate verdict (closed until the first redundancy snapshot).
historyUpdateRoleView: resolver.GetService<IHistoryUpdateRoleView>()),
DriverHostActorName);
registry.Register<DriverHostActorKey>(driverHost);
@@ -45,7 +45,7 @@ public interface ITelemetrySubscription : IDisposable
/// <summary>
/// Process-wide, node-local fan-out hub sitting between this node's own telemetry producers and the
/// (Phase-5) gRPC streaming service central dials into.
/// gRPC streaming service central dials into.
/// </summary>
/// <remarks>
/// <para>
@@ -68,6 +68,7 @@ public interface ITelemetryLocalHub
/// on a full channel) and, for the two snapshot-style items, updates the last-value cache that
/// primes future subscribers.
/// </summary>
/// <param name="item">The telemetry item to fan out.</param>
void Emit(TelemetryItem item);
/// <summary>
@@ -83,22 +84,25 @@ public interface ITelemetryLocalHub
/// priming before the reader ever drains them. The node-local cache holds only THIS node's
/// instances (a handful), so a normal large capacity leaves ample headroom.
/// </param>
/// <returns>The subscription whose reader yields the cached snapshots, then live deltas.</returns>
ITelemetrySubscription Subscribe(int boundedCapacity);
/// <summary>
/// Drops the cached Health and Resilience snapshots of a driver instance that has been removed from
/// this node, so a later <see cref="Subscribe"/> no longer replays its last-known state. Live
/// subscribers are not told; the instance simply stops emitting. Unknown ids are a no-op.
/// <para>The eviction also <b>holds</b> (#609): a removed instance's child stops asynchronously and can
/// <para>The eviction also <b>holds</b>: a removed instance's child stops asynchronously and can
/// still publish after this call (a health snapshot when an in-flight connect or subscribe finishes),
/// so until <see cref="Readmit"/> every later Health/Resilience item for the instance is dropped — not
/// cached and not fanned out.</para>
/// </summary>
/// <param name="driverInstanceId">The removed driver instance's id.</param>
void Evict(string driverInstanceId);
/// <summary>
/// Lifts an earlier <see cref="Evict"/> so a driver instance spawned again under the same id (a later
/// deployment re-adding it) publishes normally. A no-op for an id that was never evicted.
/// </summary>
/// <param name="driverInstanceId">The driver instance id to readmit.</param>
void Readmit(string driverInstanceId) { }
}
@@ -8,7 +8,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Telemetry;
/// </summary>
/// <remarks>
/// <para>
/// <b>No DPS.</b> This hub is fed only by this node's own in-process producers (a later Phase-5
/// <b>No DPS.</b> This hub is fed only by this node's own in-process producers (a later
/// task taps them). It never subscribes to cluster DistributedPubSub — see the invariant on
/// <see cref="ITelemetryLocalHub"/>.
/// </para>
@@ -37,12 +37,12 @@ public sealed class TelemetryLocalHub : ITelemetryLocalHub
// Snapshot last-value caches. Only ever mutated under _gate (kept ConcurrentDictionary so a
// Subscribe reading them under the gate is trivially safe even against any future lock-free read).
// Entries are evicted via Evict when DriverHostActor removes the instance (#609), so a
// Entries are evicted via Evict when DriverHostActor removes the instance, so a
// decommissioned driver's last-known state does not replay to new subscribers.
private readonly ConcurrentDictionary<string, TelemetryItem.Health> _healthCache = new();
private readonly ConcurrentDictionary<(string InstanceId, string HostName), TelemetryItem.Resilience> _resilienceCache = new();
// Instances evicted and not since readmitted (#609). Their late Health/Resilience items are dropped, so a
// Instances evicted and not since readmitted. Their late Health/Resilience items are dropped, so a
// removed driver's still-stopping child cannot re-prime the cache it was just evicted from. Under _gate.
private readonly HashSet<string> _evicted = new(StringComparer.Ordinal);
@@ -141,6 +141,10 @@ public sealed class TelemetryLocalHub : ITelemetryLocalHub
private readonly Guid _id;
private int _disposed;
/// <summary>Creates a subscription over a hub channel.</summary>
/// <param name="hub">The owning hub, notified on dispose.</param>
/// <param name="id">The subscription id.</param>
/// <param name="channel">The channel whose reader is exposed.</param>
public Subscription(TelemetryLocalHub hub, Guid id, Channel<TelemetryItem> channel)
{
_hub = hub;
@@ -148,8 +152,10 @@ public sealed class TelemetryLocalHub : ITelemetryLocalHub
Reader = channel.Reader;
}
/// <inheritdoc />
public ChannelReader<TelemetryItem> Reader { get; }
/// <summary>Detaches this subscription from the hub; safe to call more than once.</summary>
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
@@ -67,12 +67,11 @@ public sealed class DependencyConsumerMuxAdapter : ReceiveActor
}
/// <summary>
/// Forwards one dependency value to the consumer, <b>status code included</b> (archreview
/// 05/STAB-19).
/// Forwards one dependency value to the consumer, <b>status code included</b>
/// </summary>
/// <remarks>
/// This used to pass a hard-coded <c>0u</c> behind a comment saying quality was stripped at the
/// mux boundary. That was true when the adapter was written and stopped being true at #478/#519 —
/// mux boundary. That was true when the adapter was written and stopped being true later —
/// <see cref="VirtualTagActor.DependencyValueChanged"/> has carried the source driver's full status
/// code, sub-code and all, ever since. The stale comment outliving the fact is what kept a
/// comms-lost input arriving at the Calculation driver as <i>arrived, Good, null</i>:
@@ -31,14 +31,14 @@ public sealed class VirtualTagActor : ReceiveActor
{
public const string ScriptLogsTopic = "script-logs";
/// <summary>A dependency's value changed. <paramref name="StatusCode"/> (#478) carries the source
/// driver's OPC UA status code — since #519 including its sub-code, so a worst-of-input winner keeps
/// <summary>A dependency's value changed. <paramref name="StatusCode"/> carries the source
/// driver's OPC UA status code — including its sub-code, so a worst-of-input winner keeps
/// the reason it won — and it defaults to <see cref="OpcUaStatus.Good"/>.
/// <para><b>The virtual-tag engine consumes it</b> (archreview 02/S14). This doc used to say the
/// engine ignored it, which was true and became the defect: a Bad input was stored as a bare value,
/// the script ran against it, and the tag published a fresh-Good result over a dead source. The actor
/// now holds evaluation while any declared input is Bad and inherits the worst input's status
/// otherwise. The Calculation driver reads it through the same mux (05/STAB-19).</para></summary>
/// otherwise. The Calculation driver reads it through the same mux.</para></summary>
public sealed record DependencyValueChanged(
string TagId, object? Value, DateTime TimestampUtc, uint StatusCode = OpcUaStatus.Good);
@@ -179,7 +179,7 @@ public sealed class VirtualTagActor : ReceiveActor
/// <para>
/// The result is flagged <see cref="EvaluationResult.IsReassert"/> so the host publishes it (repairing
/// the reset node) but does NOT re-record it to the historian — it is a stale value stamped with a
/// fresh deploy-time timestamp, not a real evaluation sample (M1).
/// fresh deploy-time timestamp, not a real evaluation sample.
/// </para>
/// <para>
/// Ordering (why the re-publish lands on the freshly-materialised node, not the pre-reset one): the
@@ -320,7 +320,7 @@ public sealed class VirtualTagActor : ReceiveActor
/// </para>
/// <para>
/// Published <b>once per change of the published status</b>, and only once every declared
/// dependency has arrived — R2-03's inputs-ready gate, kept as-is, so a cold start or an actor
/// dependency has arrived — the inputs-ready gate, kept as-is, so a cold start or an actor
/// respawn does not flash Bad while the mux is still filling the map.
/// </para>
/// </remarks>
@@ -62,7 +62,7 @@ public sealed class VirtualTagHostActor : ReceiveActor
/// <see cref="NullHistoryWriter.Instance"/> (no durable historian wired), so existing call sites
/// compile unchanged and never historize.</param>
/// <param name="telemetryHub">Optional node-local live-telemetry hub passed to each spawned child so
/// its script-log entries also emit to the Phase-5 hub; null (tests) skips the emit.</param>
/// its script-log entries also emit to the live-telemetry hub; null (tests) skips the emit.</param>
/// <returns>The <see cref="Props"/> used to spawn a <see cref="VirtualTagHostActor"/>.</returns>
public static Props Props(IActorRef publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null) =>
@@ -74,7 +74,7 @@ public sealed class VirtualTagHostActor : ReceiveActor
/// <param name="evaluator">The evaluator each child uses to compute its expression.</param>
/// <param name="historyWriter">Sink for historized results; null ⇒ <see cref="NullHistoryWriter.Instance"/>.</param>
/// <param name="telemetryHub">Optional node-local live-telemetry hub passed to each spawned child so
/// its script-log entries also emit to the Phase-5 hub; null (tests) skips the emit.</param>
/// its script-log entries also emit to the live-telemetry hub; null (tests) skips the emit.</param>
public VirtualTagHostActor(IActorRef publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null)
{
@@ -227,13 +227,13 @@ public sealed class VirtualTagHostActor : ReceiveActor
_publishActor.Tell(new OpcUaPublishActor.AttributeValueUpdate(
nodeId, result.Value, result.StatusCode, result.TimestampUtc, AddressSpaceRealm.Uns));
// Historize iff the plan opted in — but NEVER for a re-assert (M1). A re-assert re-publishes a
// Historize iff the plan opted in — but NEVER for a re-assert. A re-assert re-publishes a
// stale last value stamped with a fresh deploy-time timestamp purely to repair the reset OPC UA
// node; recording it would append an artificial historian sample that never corresponded to a real
// evaluation (and, if the last state was Bad, a fabricated BadInternalError point). Reuses
// _planByVtag (kept in lock-step with _children), so no parallel map. The historian path key is the
// SAME folder-scoped NodeId we just published to. For a computed value source == server, so both
// timestamps are the evaluation time. Since #519 the result's status code IS the historian status —
// timestamps are the evaluation time. The result's status code IS the historian status —
// the two used to be derived separately here, which is why this line existed at all.
if (!result.IsReassert && _planByVtag.TryGetValue(result.VirtualTagId, out var plan) && plan.Historize)
{