feat(717): Warm non-transparent redundancy, default-off (T1-T10)

OpcUa:Redundancy:Mode (Unset default = today's server exactly; None; Warm; Hot and unknown values fail start).
- T1 options + validator + effective-URI check + boot banner; Warm needs the driver role.
- T2 metadata in OnNodeManagerStartedAsync: Warm -> NonTransparentRedundancyType, read-only
  ServerUriArray [self, peers], RedundancySupport=Warm, boot ServiceLevel 1; None -> RedundancySupport=None
  and the SDK's orphan i=11314 deleted; Unset untouched.
- T3 RedundancyStateChanged.Revision (up-number, incarnation tick, sequence); subscribers drop older
  revisions under Warm (OpcUaPublishActor, DriverHostActor); unrevisioned never makes a node Active.
- T4 WarmRoleAuthority + ComputeWarm bands (Standby 90/50, Active 250/200/100), PromoteWhilePrimaryUnreachable.
- T5 IStandbyProjection + DeferredStandbyProjection; OpcUaPublishActor runs promotion/demotion in the spec
  4.7 order (Active level last and retried; Standby level first, data degraded regardless).
- T6 EquipmentVariableState read projection (BadOutOfService/null); Warm Standby refuses writes BadInvalidState.
- T7 D4 mechanism adopted after T0: ordinary-tag marker on MonitoredItemNotification.Message validated by
  (ClientHandle, DataValue); first-delivery decision keyed by (SubscriptionId, SequenceNumber); the SDK's
  cached copy is never mutated.
- T8 queue current/BadOutOfService to live ordinary-tag items ignoring filters.
- T9 alarm stamp/deliver split (suppressed on Standby), Part 9 methods refused on Standby, promotion
  refresh via ISubscription.ConditionRefresh2Async on every live event item.
- T10 deploy-time RedundancyMode cross-check + six instruments.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
Joseph Doherty
2026-11-13 03:26:36 -05:00
parent dcff5ae994
commit 7829b937d1
27 changed files with 3056 additions and 29 deletions
@@ -258,6 +258,52 @@ public static class DeploymentArtifact
}
}
/// <summary>
/// Gitea #717 spec §3: the <c>ServerCluster.RedundancyMode</c> of this node's cluster as the artifact carries it
/// (<c>None</c>/<c>Warm</c>/<c>Hot</c>), for the deploy-time cross-check against <c>OpcUa:Redundancy:Mode</c>.
/// A single-cluster artifact answers for its only cluster; a multi-cluster one for the cluster of this node's
/// <c>ClusterNode</c> row. Null when the artifact does not say (empty, malformed, no matching cluster).
/// </summary>
/// <param name="blob">The deployment artifact.</param>
/// <param name="nodeId">This node's <c>host:port</c> id.</param>
/// <returns>The mode name, or null.</returns>
public static string? ReadClusterRedundancyMode(ReadOnlySpan<byte> blob, string nodeId)
{
if (blob.IsEmpty) return null;
try
{
using var parsed = Open(blob.ToArray());
var root = parsed.Root;
if (!root.TryGetProperty("Clusters", out var clusters) || clusters.ValueKind != JsonValueKind.Array) return null;
var scope = parsed.ResolveClusterScope(nodeId);
JsonElement? match = null;
foreach (var cluster in clusters.EnumerateArray())
{
if (cluster.ValueKind != JsonValueKind.Object) continue;
if (scope.Mode == ClusterFilterMode.None) { match = cluster; break; }
if (scope.Mode == ClusterFilterMode.ScopeTo
&& string.Equals(cluster.TryGetProperty("ClusterId", out var cid) && cid.ValueKind == JsonValueKind.String ? cid.GetString() : null, scope.ClusterId, StringComparison.OrdinalIgnoreCase))
{
match = cluster;
break;
}
}
if (match is not { } m || !m.TryGetProperty("RedundancyMode", out var mode)) return null;
return mode.ValueKind switch
{
JsonValueKind.String => mode.GetString(),
JsonValueKind.Number when mode.TryGetInt32(out var n) && Enum.IsDefined(typeof(Configuration.Enums.RedundancyMode), n)
=> ((Configuration.Enums.RedundancyMode)n).ToString(),
_ => null,
};
}
catch (JsonException)
{
return null;
}
}
/// <summary>
/// Resolve how a node should scope a deployment artifact to its own ClusterId. Single-cluster
/// (or legacy) artifacts resolve to <see cref="ClusterFilterMode.None"/> so every existing
@@ -789,7 +789,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
DriverWriteBounds? writeBounds = null,
TimeProvider? writeClock = null,
IScriptRunner? scriptedAlarmRunner = null,
TimeSpan? childShutdownTimeout = null) =>
TimeSpan? childShutdownTimeout = null,
bool enforceSnapshotOrdering = false) =>
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
@@ -803,7 +804,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
alarmStateStore, telemetryHub, primaryRoleSource, historizationRoleView,
sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay,
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout));
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
enforceSnapshotOrdering));
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
/// <param name="dbFactory">Database context factory for configuration database access.</param>
@@ -938,8 +940,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
DriverWriteBounds? writeBounds = null,
TimeProvider? writeClock = null,
IScriptRunner? scriptedAlarmRunner = null,
TimeSpan? childShutdownTimeout = null)
TimeSpan? childShutdownTimeout = null,
bool enforceSnapshotOrdering = false)
{
_snapshotOrdering = enforceSnapshotOrdering ? new SnapshotRevisionGate() : null;
_childShutdownTimeout = childShutdownTimeout;
_scriptedAlarmRunner = scriptedAlarmRunner;
_writeBounds = writeBounds ?? DriverWriteBounds.Default;
@@ -2552,8 +2556,21 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// the cached role unchanged; when this node has a real driver peer (count &gt; 1) that omission is the
/// 03/S5 identity-mismatch shape, logged ONCE at Warning. Mirrors
/// <c>ScriptedAlarmHostActor.OnRedundancyStateChanged</c> / <c>OpcUaPublishActor</c>.</summary>
/// <summary>Gitea #717: the snapshot order gate under Warm; null (no ordering, today's behaviour) otherwise.</summary>
private readonly SnapshotRevisionGate? _snapshotOrdering;
private void OnRedundancyStateChanged(RedundancyStateChanged msg)
{
// Gitea #717 spec §4.2, under OpcUa:Redundancy:Mode=Warm only (Unset/None keep today's unconditional replace):
// a snapshot older than the last accepted one — a late heartbeat of an old singleton incarnation — is dropped,
// so it cannot overwrite the new incarnation's roles. An unrevisioned snapshot (pre-#717 publisher) still feeds
// the gates, as before.
if (_snapshotOrdering?.Offer(msg) == SnapshotRejection.OlderRevision)
{
OtOpcUaTelemetry.SnapshotRejected.Add(1, new KeyValuePair<string, object?>("reason", "older_revision"));
return;
}
_redundancySnapshotReceived = true;
var local = msg.Nodes.FirstOrDefault(n => n.NodeId == _localNode);
if (local is not null)
@@ -14,6 +14,7 @@ using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Health;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
namespace ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
@@ -326,7 +327,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
bool dbLess = false,
IDataPlaneAuthoritySink? dataPlaneAuthority = null,
Func<DateTime>? utcNow = null,
IOpcUaEndpointState? endpointState = null) =>
IOpcUaEndpointState? endpointState = null,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null) =>
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
sink ?? NullOpcUaAddressSpaceSink.Instance,
serviceLevel ?? NullServiceLevelPublisher.Instance,
@@ -341,7 +344,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
dbLess,
dataPlaneAuthority,
utcNow,
endpointState)).WithDispatcher(DispatcherId);
endpointState,
redundancy,
standbyProjection)).WithDispatcher(DispatcherId);
/// <summary>Test-only Props that omits the pinned-dispatcher requirement and skips the
/// DPS subscribe so unit tests can spin up the actor on a vanilla TestKit cluster.</summary>
@@ -385,7 +390,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
bool dbLess = false,
IDataPlaneAuthoritySink? dataPlaneAuthority = null,
Func<DateTime>? utcNow = null,
IOpcUaEndpointState? endpointState = null) =>
IOpcUaEndpointState? endpointState = null,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null) =>
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
sink ?? NullOpcUaAddressSpaceSink.Instance,
serviceLevel ?? NullServiceLevelPublisher.Instance,
@@ -400,7 +407,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
dbLess,
dataPlaneAuthority,
utcNow,
endpointState));
endpointState,
redundancy,
standbyProjection));
/// <summary>Test-only Props exposing the deferred-write bound and the plan-step seams.</summary>
internal static Props PropsForTests(
@@ -461,10 +470,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
bool dbLess = false,
IDataPlaneAuthoritySink? dataPlaneAuthority = null,
Func<DateTime>? utcNow = null,
IOpcUaEndpointState? endpointState = null)
IOpcUaEndpointState? endpointState = null,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null)
: this(sink, serviceLevel, subscribeRedundancyTopic, localNode, dbFactory, applier, dbHealthProbe, staleWindow,
probeFreshnessWindow, healthTickInterval, dbLess, dataPlaneAuthority, utcNow, DefaultDeferredWriteCapacity, hooks: null,
endpointState)
endpointState, redundancy, standbyProjection)
{
}
@@ -488,8 +499,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
Func<DateTime>? utcNow,
int deferredWriteCapacity,
TestHooks? hooks,
IOpcUaEndpointState? endpointState)
IOpcUaEndpointState? endpointState,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null)
{
_redundancy = redundancy ?? WarmRedundancySettings.Unset;
_standbyProjection = standbyProjection;
_deferred = new DeferredWrites(Math.Max(1, deferredWriteCapacity));
_hooks = hooks;
_sink = sink;
@@ -523,6 +538,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
Receive<HealthTick>(_ => OnHealthTick());
Receive<PeerOpcUaProbeActor.OpcUaProbeResult>(HandlePeerProbe);
Receive<SubscribeAck>(_ => { /* PubSub ack */ });
// Gitea #717 spec §4.1 / owner answer Q2: under Warm the verdict re-derives on membership and reachability, not
// only on snapshots. Nothing subscribes these under Unset/None.
Receive<ClusterEvent.IMemberEvent>(_ => RecomputeServiceLevel());
Receive<ClusterEvent.IReachabilityEvent>(_ => RecomputeServiceLevel());
Receive<ClusterEvent.CurrentClusterState>(_ => RecomputeServiceLevel());
Receive<WarmRetry>(_ => RecomputeServiceLevel());
}
/// <summary>
@@ -543,6 +564,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
base.PreRestart(reason, message);
}
/// <inheritdoc />
protected override void PostStop()
{
if (_redundancy.IsWarm)
{
try { _cluster.Unsubscribe(Self); }
catch (Exception) { /* the cluster is shutting down with us */ }
}
base.PostStop();
}
/// <inheritdoc />
protected override void PreStart()
{
@@ -551,6 +584,20 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
DistributedPubSub.Get(Context.System).Mediator.Tell(new Subscribe(RedundancyStateTopic, Self));
}
if (_redundancy.IsWarm)
{
OtOpcUaTelemetry.SetWarmRole(0);
try
{
_cluster.Subscribe(Self, ClusterEvent.InitialStateAsEvents,
typeof(ClusterEvent.IMemberEvent), typeof(ClusterEvent.IReachabilityEvent));
}
catch (Exception ex)
{
_log.Warning(ex, "OpcUaPublish: Warm redundancy could not subscribe to cluster membership; the verdict re-derives on snapshots only");
}
}
// DB-backed nodes refresh their cached probe status; DB-less nodes still need periodic
// snapshot/probe-verdict age checks even when no new messages arrive. Legacy nodes keep
// their role-only behavior without a timer.
@@ -672,7 +719,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
}
private void HandleRebuild(RebuildAddressSpace msg) => StartRebuild(msg, Sender);
private void HandleRebuild(RebuildAddressSpace msg)
{
if (msg.Artifact is { Length: > 0 } artifact) CheckRedundancyMode(artifact);
StartRebuild(msg, Sender);
}
/// <summary>
/// The entry half of a rebuild, on the actor thread. The raw-sink fallback (no applier) and the
@@ -1465,26 +1516,34 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
}
private void HandleServiceLevelChanged(ServiceLevelChanged msg)
private void HandleServiceLevelChanged(ServiceLevelChanged msg) => TryPublishServiceLevel(msg.ServiceLevel);
/// <summary>The dedup/publish/metric step behind <see cref="ServiceLevelChanged"/>; synchronous so a Warm
/// transition can order it against the projection steps (spec §4.7).</summary>
/// <param name="level">The level to publish.</param>
/// <returns>True when the level is published (or already was).</returns>
private bool TryPublishServiceLevel(byte level)
{
// Always publish the FIRST computed level, even if it equals the byte-default 0. Otherwise a
// node starting Detached/role-less (first level = 0) would be dedup'd away, leaving the SDK's
// built-in default (255 = full service) standing — a degraded node wrongly advertising 255.
if (_publishedAtLeastOnce && msg.ServiceLevel == _lastServiceLevel) return;
if (_publishedAtLeastOnce && level == _lastServiceLevel) return true;
try
{
_serviceLevel.Publish(msg.ServiceLevel);
_lastServiceLevel = msg.ServiceLevel;
_serviceLevel.Publish(level);
_lastServiceLevel = level;
_publishedAtLeastOnce = true;
OtOpcUaTelemetry.ServiceLevelChange.Add(1,
new KeyValuePair<string, object?>("level", msg.ServiceLevel));
_log.Debug("OpcUaPublish: ServiceLevel={Level}", msg.ServiceLevel);
new KeyValuePair<string, object?>("level", level));
_log.Debug("OpcUaPublish: ServiceLevel={Level}", level);
return true;
}
catch (Exception ex)
{
// A failed write may be partially applied; even a previous successful value must retry.
_publishedAtLeastOnce = false;
_log.Warning(ex, "OpcUaPublish: ServiceLevel publisher threw at level {Level}", msg.ServiceLevel);
_log.Warning(ex, "OpcUaPublish: ServiceLevel publisher threw at level {Level}", level);
return false;
}
}
@@ -1494,6 +1553,28 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// wired) or via the legacy role-only seam (back-compat / bootstrap).</summary>
private void HandleRedundancyStateChanged(RedundancyStateChanged msg)
{
if (_redundancy.IsWarm)
{
// Gitea #717 spec §4.2: under Warm a snapshot older than the last accepted one (a late heartbeat from an old
// singleton incarnation) is dropped outright. An unrevisioned one (a pre-#717 publisher mid-upgrade) still
// feeds the health inputs but can never make this node Active. Unset/None keep today's unconditional
// replace below.
switch (_revisionGate.Offer(msg))
{
case SnapshotRejection.OlderRevision:
OtOpcUaTelemetry.SnapshotRejected.Add(1, new KeyValuePair<string, object?>("reason", "older_revision"));
_log.Debug("OpcUaPublish: dropped redundancy snapshot {Revision} (last accepted {Last})",
msg.Revision, _revisionGate.LastAccepted);
return;
case SnapshotRejection.Unrevisioned:
OtOpcUaTelemetry.SnapshotRejected.Add(1, new KeyValuePair<string, object?>("reason", "unrevisioned"));
break;
default:
_acceptedSnapshot = msg;
break;
}
}
_lastSnapshot = msg;
RecomputeServiceLevel();
}
@@ -1576,6 +1657,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private void RecomputeServiceLevel()
{
if (_localNode is null || _lastSnapshot is null) return;
if (_redundancy.IsWarm)
{
RecomputeWarm();
return;
}
var entry = _lastSnapshot.Nodes.FirstOrDefault(n => n.NodeId == _localNode.Value);
@@ -1635,6 +1721,197 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
Self.Tell(new ServiceLevelChanged(ServiceLevelCalculator.Compute(inputs)));
}
// ---------------------------------------------------------------- Warm redundancy (Gitea #717)
private sealed class WarmRetry { public static readonly WarmRetry Instance = new(); private WarmRetry() { } }
private readonly WarmRedundancySettings _redundancy;
private readonly IStandbyProjection? _standbyProjection;
private readonly SnapshotRevisionGate _revisionGate = new();
/// <summary>The latest ACCEPTED revisioned snapshot — the only one the Warm verdict reads (spec §4.2).</summary>
private RedundancyStateChanged? _acceptedSnapshot;
/// <summary>The role the data plane is in. A Warm node manager boots Standby, so this starts Standby.</summary>
private WarmRole _warmRole = WarmRole.Standby;
/// <summary>A promotion whose Active ServiceLevel publish failed (spec §4.7): the data plane is Active and the
/// level is retried; the Standby level stays visible meanwhile, never the reverse.</summary>
private bool _promotionLevelPending;
private DateTime? _disagreeSinceUtc;
private bool _disagreementWarned;
/// <summary>How long membership and snapshot may disagree before a Warning (two heartbeats, spec §4.1).</summary>
internal static readonly TimeSpan WarmDisagreementWarning = TimeSpan.FromSeconds(20);
/// <summary>The current Warm role (test observation).</summary>
internal WarmRole CurrentWarmRole => _warmRole;
/// <summary>A promoted node whose Active ServiceLevel publish is being retried (test observation).</summary>
internal bool PromotionLevelPending => _promotionLevelPending;
/// <summary>
/// The Warm ServiceLevel + role path (spec §4.1, §4.3, §4.7): the health facts the non-Warm paths use, the
/// Warm verdict, then a transition in the fixed step order when the verdict changed, else just the band.
/// </summary>
private void RecomputeWarm()
{
var self = _localNode!.Value;
var entry = _lastSnapshot!.Nodes.FirstOrDefault(n => n.NodeId == self);
var now = _utcNow();
var memberState = SafeSelfStatus();
var listening = EndpointListening();
bool dbReachable;
bool stale;
if (_dbLess || _dbHealthProbe is null || _lastDbHealth is null)
{
dbReachable = true;
stale = entry is null || (now - entry.AsOfUtc) > _staleWindow;
}
else
{
dbReachable = _lastDbHealth.Reachable;
stale = !_lastDbHealth.Reachable
|| (now - _lastDbHealth.AsOfUtc) > _staleWindow
|| entry is null || (now - entry.AsOfUtc) > _staleWindow;
}
var verdict = EvaluateWarmVerdict(self, memberState, listening);
TrackDisagreement(verdict, now);
var detached = entry is null || entry.Role == RedundancyRole.Detached;
var inputs = new NodeHealthInputs(memberState, dbReachable, OpcUaProbeOk(), stale, IsDriverPrimary: false, listening);
var target = detached ? WarmRole.Standby : verdict.Role;
var level = detached ? (byte)0 : ServiceLevelCalculator.ComputeWarm(inputs, target == WarmRole.Active);
ApplyWarmTransition(target, level, verdict.Reason);
}
private WarmVerdict EvaluateWarmVerdict(NodeId self, MemberStatus memberState, bool listening)
{
NodeId? oldest = null, oldestReachable = null;
var primaryUnreachable = false;
var snapshotPrimary = _acceptedSnapshot?.Nodes.FirstOrDefault(n => n.Role == RedundancyRole.Primary)?.NodeId;
try
{
var state = _cluster.State;
var unreachable = state.Unreachable.ToHashSet();
oldest = WarmRoleAuthority.OldestUpMember(state.Members, "driver");
oldestReachable = WarmRoleAuthority.OldestUpMember(state.Members, "driver", unreachable);
primaryUnreachable = snapshotPrimary is { } sp && unreachable.Any(m => WarmRoleAuthority.ToNodeId(m) == sp);
}
catch (Exception ex)
{
_log.Debug(ex, "OpcUaPublish: cluster state unavailable for the Warm verdict; treating membership as unknown");
}
return WarmRoleAuthority.Evaluate(new WarmRoleInputs(
self, memberState == MemberStatus.Up, listening, oldest, oldestReachable,
HasAcceptedSnapshot: _acceptedSnapshot is not null, snapshotPrimary, primaryUnreachable,
_redundancy.PromoteWhilePrimaryUnreachable));
}
private void TrackDisagreement(WarmVerdict verdict, DateTime now)
{
if (!verdict.Disagreement)
{
_disagreeSinceUtc = null;
_disagreementWarned = false;
return;
}
_disagreeSinceUtc ??= now;
if (_disagreementWarned || now - _disagreeSinceUtc.Value <= WarmDisagreementWarning) return;
_disagreementWarned = true;
_log.Warning(
"OpcUaPublish: Warm redundancy — cluster membership and the redundancy snapshot (revision {Revision}) have disagreed about this node being Primary for more than {Seconds}s; the node stays {Role}",
_revisionGate.LastAccepted, WarmDisagreementWarning.TotalSeconds, _warmRole);
}
/// <summary>
/// Moves the data plane to <paramref name="target"/> in the spec §4.7 order and publishes
/// <paramref name="level"/>. Invariant: an Active-band ServiceLevel is never visible while the projection is
/// closed — a promotion publishes the level LAST and, if that publish fails, retries it; a demotion publishes
/// the Standby level FIRST and degrades the data whether or not that publish succeeded (failing safe).
/// </summary>
private void ApplyWarmTransition(WarmRole target, byte level, string reason)
{
if (target == _warmRole)
{
if (!TryPublishServiceLevel(level) && target == WarmRole.Active) ScheduleWarmRetry();
else if (target == WarmRole.Active) _promotionLevelPending = false;
return;
}
var projection = _standbyProjection;
if (target == WarmRole.Active)
{
projection?.SetDataProjection(false); // 1. open the read projection
projection?.QueueCurrentToLiveItems(false); // 2. current Good value to every live data item
projection?.SetStandbyDelivery(false); // 3. first deliveries decided Active
projection?.SetAlarmSuppression(false); // 4. new alarm events delivered
projection?.RefreshAllEventItems(); // 5. promotion refresh on every live event item
_warmRole = WarmRole.Active;
if (TryPublishServiceLevel(level)) // 6. Active ServiceLevel, last
{
_promotionLevelPending = false;
}
else
{
_promotionLevelPending = true;
ScheduleWarmRetry();
}
}
else
{
TryPublishServiceLevel(level); // 1. Standby ServiceLevel, first (continue on failure)
projection?.SetStandbyDelivery(true); // 2. the D4 boundary
projection?.SetAlarmSuppression(true); // 3. suppress new alarm events
projection?.SetDataProjection(true); // 4. close the read projection
projection?.QueueCurrentToLiveItems(true); // 5. BadOutOfService to every live data item
_warmRole = WarmRole.Standby;
_promotionLevelPending = false;
}
OtOpcUaTelemetry.SetWarmRole(_warmRole == WarmRole.Active ? 1 : 0);
OtOpcUaTelemetry.WarmTransition.Add(1,
new KeyValuePair<string, object?>("direction", target == WarmRole.Active ? "promote" : "demote"),
new KeyValuePair<string, object?>("reason", reason));
_log.Info(
"OpcUaPublish: Warm redundancy {Direction} to {Role} (reason={Reason}, revision={Revision}, ServiceLevel={Level})",
target == WarmRole.Active ? "promotion" : "demotion", _warmRole, reason, _revisionGate.LastAccepted, level);
}
/// <summary>
/// Gitea #717 spec §3 deploy-time cross-check: under <c>None</c> or <c>Warm</c>, an artifact whose cluster
/// <c>RedundancyMode</c> disagrees with the local mode (<c>Hot</c> included, owner answer Q5) logs an Error and
/// counts <c>otopcua.redundancy.mode_mismatch</c>. The node keeps its local mode — the only value available
/// before SDK start. <c>Unset</c> has opted out and is not checked.
/// </summary>
/// <param name="artifact">The applied artifact bytes.</param>
private void CheckRedundancyMode(byte[] artifact)
{
if (_redundancy.Mode == OpcUaRedundancyMode.Unset || _localNode is null) return;
string? clusterMode;
try
{
clusterMode = DeploymentArtifact.ReadClusterRedundancyMode(artifact, _localNode.Value.Value);
}
catch (Exception ex)
{
_log.Debug(ex, "OpcUaPublish: could not read the artifact's cluster RedundancyMode");
return;
}
if (clusterMode is null) return;
if (string.Equals(clusterMode, _redundancy.Mode.ToString(), StringComparison.OrdinalIgnoreCase)) return;
OtOpcUaTelemetry.RedundancyModeMismatch.Add(1,
new KeyValuePair<string, object?>("local", _redundancy.Mode.ToString()),
new KeyValuePair<string, object?>("cluster", clusterMode));
_log.Error(
"OpcUaPublish: the deployed ServerCluster.RedundancyMode for this node's cluster is {ClusterMode} but OpcUa:Redundancy:Mode is {LocalMode}; the node keeps running as {LocalMode} (local configuration is the authority — fix whichever is wrong)",
clusterMode, _redundancy.Mode, _redundancy.Mode);
}
private void ScheduleWarmRetry() => Timers.StartSingleTimer("warm-retry", WarmRetry.Instance, TimeSpan.FromSeconds(1));
/// <summary>The legacy role-only ServiceLevel switch (primary-leader → 240, primary → 200,
/// secondary → 100, _ → 0). Preserved as the back-compat / bootstrap seam.</summary>
private static byte LegacyRoleOnly(NodeRedundancyState entry) => entry.Role switch
@@ -0,0 +1,109 @@
using Akka.Cluster;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
/// <summary>The Warm role (Gitea #717 spec §4.1).</summary>
public enum WarmRole
{
/// <summary>Degraded standby: projected data, suppressed new alarm events, Degraded-band ServiceLevel.</summary>
Standby,
/// <summary>Serves data and alarms; Healthy-band ServiceLevel.</summary>
Active,
}
/// <summary>The facts the Warm verdict is a pure function of.</summary>
/// <param name="Self">This node's canonical <c>host:port</c> id.</param>
/// <param name="SelfUp">This node's own member status is Up.</param>
/// <param name="EndpointListening">This node's OPC UA endpoint did not fail to start (#762).</param>
/// <param name="OldestUpDriver">The oldest Up <c>driver</c> member in this node's OWN cluster state (the singleton
/// placement rule), or null when there is none.</param>
/// <param name="OldestReachableUpDriver">The same, ignoring members this node sees as unreachable.</param>
/// <param name="HasAcceptedSnapshot">A revisioned snapshot has been accepted (spec §4.2). Unrevisioned snapshots
/// never count.</param>
/// <param name="SnapshotPrimary">The Primary named by the latest accepted revisioned snapshot, or null.</param>
/// <param name="SnapshotPrimaryUnreachable">This node sees <paramref name="SnapshotPrimary"/> as unreachable.</param>
/// <param name="PromoteWhilePrimaryUnreachable">The owner-answer-Q2 option (default on).</param>
public readonly record struct WarmRoleInputs(
NodeId Self,
bool SelfUp,
bool EndpointListening,
NodeId? OldestUpDriver,
NodeId? OldestReachableUpDriver,
bool HasAcceptedSnapshot,
NodeId? SnapshotPrimary,
bool SnapshotPrimaryUnreachable,
bool PromoteWhilePrimaryUnreachable);
/// <summary>The verdict and why.</summary>
/// <param name="Role">Active or Standby.</param>
/// <param name="Reason">A short reason for the transition metric/log: <c>boot</c>, <c>endpoint</c>,
/// <c>membership</c>, <c>snapshot</c>, <c>unreachable-primary</c> or <c>agreed</c>.</param>
/// <param name="Disagreement">Membership (2) and snapshot (3) disagree about whether this node is Primary.</param>
public readonly record struct WarmVerdict(WarmRole Role, string Reason, bool Disagreement);
/// <summary>
/// The Warm role verdict (Gitea #717 spec §4.1), a pure function so every row is unit-testable. Active iff the
/// node is Up and listening, its own cluster state names it the oldest Up driver member, and the latest accepted
/// revisioned snapshot names it Primary. Anything else — no snapshot yet, an unrevisioned snapshot, a
/// disagreement — is Standby. With <see cref="WarmRoleInputs.PromoteWhilePrimaryUnreachable"/> the survivor of a
/// crashed Primary goes Active once that Primary is unreachable, before <c>auto-down</c> removes it.
/// </summary>
/// <remarks>
/// This is a separate output from <c>PrimaryGatePolicy</c>, whose lone-node allow is unchanged for writes and
/// acks (D7).
/// </remarks>
public static class WarmRoleAuthority
{
/// <summary>Evaluates the verdict.</summary>
/// <param name="i">The inputs.</param>
/// <returns>The verdict.</returns>
public static WarmVerdict Evaluate(in WarmRoleInputs i)
{
if (!i.SelfUp) return new(WarmRole.Standby, "membership", false);
if (!i.EndpointListening) return new(WarmRole.Standby, "endpoint", false);
if (!i.HasAcceptedSnapshot) return new(WarmRole.Standby, "boot", false);
var membershipSaysSelf = i.OldestUpDriver == i.Self;
var snapshotSaysSelf = i.SnapshotPrimary == i.Self;
var disagreement = membershipSaysSelf != snapshotSaysSelf;
if (membershipSaysSelf && snapshotSaysSelf) return new(WarmRole.Active, "agreed", false);
// Owner answer Q2: a SIGKILLed Primary stays an Up-but-unreachable member until auto-down removes it, and the
// singleton usually died with it. Evaluate (2) and (3) with unreachable members excluded.
if (i.PromoteWhilePrimaryUnreachable
&& i.OldestReachableUpDriver == i.Self
&& (snapshotSaysSelf || (i.SnapshotPrimary is not null && i.SnapshotPrimaryUnreachable)))
{
return new(WarmRole.Active, "unreachable-primary", disagreement);
}
return new(WarmRole.Standby, membershipSaysSelf ? "snapshot" : "membership", disagreement);
}
/// <summary>The oldest Up member carrying <paramref name="role"/> (the singleton placement rule), optionally
/// ignoring <paramref name="unreachable"/> members.</summary>
/// <param name="members">The current members.</param>
/// <param name="role">The role.</param>
/// <param name="unreachable">Members to ignore, or null.</param>
/// <returns>Its canonical node id, or null.</returns>
public static NodeId? OldestUpMember(IEnumerable<Member> members, string role, IReadOnlySet<Member>? unreachable = null)
{
Member? oldest = null;
foreach (var m in members)
{
if (m.Status != MemberStatus.Up || !m.HasRole(role)) continue;
if (unreachable is not null && unreachable.Contains(m)) continue;
if (oldest is null || m.IsOlderThan(oldest)) oldest = m;
}
return oldest is null ? null : ToNodeId(oldest);
}
/// <summary>The canonical <c>host:port</c> id of a member (the RedundancyStateActor format).</summary>
/// <param name="m">The member.</param>
/// <returns>The node id.</returns>
public static NodeId ToNodeId(Member m) => NodeId.Parse($"{m.Address.Host ?? string.Empty}:{m.Address.Port ?? 0}");
}
@@ -566,6 +566,9 @@ public static class ServiceCollectionExtensions
// Optional: a harness that builds this graph without the hosted service registers none, and both
// consumers then behave as if the endpoint were listening (the pre-#762 behaviour).
var endpointState = resolver.GetService<IOpcUaEndpointState>();
// Gitea #717: OpcUa:Redundancy (registered by the Host from the validated OpcUa options). Absent in harnesses ⇒
// Unset ⇒ today's behaviour. The standby projection is late-bound like the ServiceLevel publisher.
var redundancy = resolver.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
var publishActor = system.ActorOf(
OpcUaPublishActor.Props(
sink: addressSpaceSink,
@@ -576,7 +579,9 @@ public static class ServiceCollectionExtensions
dbHealthProbe: dbHealth,
dbLess: dbFactory is null,
dataPlaneAuthority: dataPlaneAuthority,
endpointState: endpointState),
endpointState: endpointState,
redundancy: redundancy,
standbyProjection: redundancy.IsWarm ? resolver.GetService<DeferredStandbyProjection>() : null),
OpcUaPublishActorName);
registry.Register<OpcUaPublishActorKey>(publishActor);
@@ -670,7 +675,9 @@ public static class ServiceCollectionExtensions
// lmxopcua#780: the out-of-process runner when Scripting:Runner:Seams lists ScriptedAlarm. Null under
// the InProcess default, when the seam is not listed, and in test graphs that register no provider.
scriptedAlarmRunner: resolver.GetService<ZB.MOM.WW.OtOpcUa.Core.Scripting.IScriptRunnerProvider>()
?.ForSeam(ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptSeam.ScriptedAlarm)),
?.ForSeam(ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptSeam.ScriptedAlarm),
// Gitea #717 spec §4.2: drop older redundancy snapshots under Warm only.
enforceSnapshotOrdering: redundancy.IsWarm),
DriverHostActorName);
registry.Register<DriverHostActorKey>(driverHost);