Merge #1113: gRPC origin already retires a respawned driver's samples (pinned by test); config-change respawn keeps the comms latch trimmed to kept refs; audit warning names the real status; stubbed drivers' value nodes read BadConfigurationError; slow-connect behaviour documented

This commit is contained in:
Joseph Doherty
2026-12-05 03:06:25 -05:00
7 changed files with 499 additions and 20 deletions
@@ -58,6 +58,12 @@ public static class OpcUaStatus
/// (lmxopcua#787) — distinct from <see cref="BadInternalError"/>, which means the tag's own script failed.</summary>
public const uint BadOutOfService = 0x808D0000;
/// <summary>The source is misconfigured and will produce nothing until the configuration changes. The status a
/// driver's value nodes carry while that driver runs as a STUB — its type has no factory on this node, the factory
/// rejected its config, or the type is not allowed on the node's roles (lmxopcua#1113) — instead of
/// <see cref="BadWaitingForInitialData"/>, which would promise a first value that can never come.</summary>
public const uint BadConfigurationError = 0x80890000;
/// <summary>Part 4 severity bucket of <paramref name="statusCode"/>: the top two bits.</summary>
/// <param name="statusCode">The status code to classify.</param>
/// <returns>0 for Good, 1 for Uncertain, 2 or 3 for Bad.</returns>
@@ -689,6 +689,14 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// </summary>
private readonly Dictionary<string, HashSet<string>> _commsLatched = new(StringComparer.Ordinal);
/// <summary>
/// Gitea #1113 item 3: drivers whose <see cref="_commsLatched"/> refs were re-stamped
/// <see cref="OpcUaStatus.BadWaitingForInitialData"/> by a respawn / Restart after the comms-loss stamp
/// (<see cref="StampValueNodesAwaitingNewDriver"/>), so the recovery audit names the status those nodes
/// actually carry. Cleared with the latch and by a fresh comms-loss stamp.
/// </summary>
private readonly HashSet<string> _commsLatchReplaced = new(StringComparer.Ordinal);
/// <summary>Per-driver rate limit for the supervision-reprovision hook (see
/// <see cref="DefaultReprovisionBackoff"/>).</summary>
private readonly TimeSpan _reprovisionBackoff;
@@ -1845,6 +1853,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_opcUaPublishActor?.Tell(
new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, blob, CatalogAttempt: _catalogAttempt,
ArtifactRevision: ArtifactRevisionOf(blob)));
StampStubbedDriverValueNodes();
if (_opcUaPublishActor is null && _catalogAttempt is not null)
_catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: true);
return true;
@@ -2348,6 +2357,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
var latched = new HashSet<string>(entries.Count, StringComparer.Ordinal);
foreach (var (rawPath, _) in entries) latched.Add(rawPath);
_commsLatched[driverInstanceId] = latched;
// The nodes carry BadNoCommunication again, whatever a respawn stamped before.
_commsLatchReplaced.Remove(driverInstanceId);
// A previous reconnect's audit is now meaningless — this driver is down again.
Timers.Cancel(CommsAuditTimerKey(driverInstanceId));
@@ -2364,7 +2375,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
{
if (!_commsLatched.TryGetValue(driverInstanceId, out var latched)) return;
if (!latched.Remove(fullReference)) return;
if (latched.Count == 0) _commsLatched.Remove(driverInstanceId);
if (latched.Count == 0) ForgetCommsLatch(driverInstanceId);
}
/// <summary>
@@ -2384,6 +2395,41 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
private static string CommsAuditTimerKey(string driverInstanceId) => $"comms-audit:{driverInstanceId}";
/// <summary>Drops <paramref name="driverInstanceId"/>'s comms-loss latch and its replaced marker.</summary>
/// <param name="driverInstanceId">The driver whose latch ends.</param>
private void ForgetCommsLatch(string driverInstanceId)
{
_commsLatched.Remove(driverInstanceId);
_commsLatchReplaced.Remove(driverInstanceId);
}
/// <summary>
/// Gitea #1113 item 2: trims every outstanding comms-loss latch to the value refs the just-rebuilt index still
/// routes for that driver, so a ref a deploy dropped (or a respawn's new composition no longer carries) can never
/// be reported by the recovery audit — it cannot re-publish a ref nobody subscribes it to. A latch left empty is
/// dropped. Runs after every reindex (<see cref="ApplyDesiredSubscriptions"/>), which is also where a
/// config-change respawn's kept latch (<see cref="StopChild"/>) meets the new composition — before the new
/// incarnation's <c>Connected</c> can arm the audit, since both happen inside the same apply message.
/// </summary>
private void TrimCommsLatchesToIndex()
{
if (_commsLatched.Count == 0) return;
foreach (var driverId in _commsLatched.Keys.ToArray())
{
var latched = _commsLatched[driverId];
if (!_valueRefsByDriver.TryGetValue(driverId, out var entries) || entries.Count == 0)
{
ForgetCommsLatch(driverId);
continue;
}
var current = new HashSet<string>(entries.Count, StringComparer.Ordinal);
foreach (var (rawPath, _) in entries) current.Add(rawPath);
latched.IntersectWith(current);
if (latched.Count == 0) ForgetCommsLatch(driverId);
}
}
/// <summary>
/// The 03/S15 tripwire firing: refs this host latched <c>BadNoCommunication</c> that the driver has
/// still not re-published <see cref="_commsRecoveryAuditDelay"/> after it reconnected.
@@ -2406,10 +2452,16 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
{
if (!_commsLatched.TryGetValue(msg.DriverInstanceId, out var latched) || latched.Count == 0)
{
_commsLatched.Remove(msg.DriverInstanceId);
ForgetCommsLatch(msg.DriverInstanceId);
return;
}
// #1113 item 3: a respawn / Restart since the outage re-stamped those nodes awaiting-first-value — name the
// status they actually carry.
var latchedStatus = _commsLatchReplaced.Contains(msg.DriverInstanceId)
? nameof(OpcUaStatus.BadWaitingForInitialData)
: nameof(OpcUaStatus.BadNoCommunication);
var driverType = _children.TryGetValue(msg.DriverInstanceId, out var child) ? child.DriverType : "unknown";
OtOpcUaTelemetry.DriverCommsLatchedRefs.Add(
latched.Count,
@@ -2417,13 +2469,16 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
new KeyValuePair<string, object?>("driver_type", driverType));
_log.Warning(
"DriverHost {Node}: driver {Driver} ({Type}) — {Count} ref(s) still BadNoCommunication {Delay} after reconnect; "
"DriverHost {Node}: driver {Driver} ({Type}) — {Count} ref(s) still {Status} {Delay} after reconnect; "
+ "the driver did not re-publish them (missing initial push, or a value-only dedup swallowed an unchanged value). "
+ "First: {First}",
_localNode, msg.DriverInstanceId, driverType, latched.Count, _commsRecoveryAuditDelay,
latched.OrderBy(r => r, StringComparer.Ordinal).First());
new object[]
{
_localNode, msg.DriverInstanceId, driverType, latched.Count, latchedStatus, _commsRecoveryAuditDelay,
latched.OrderBy(r => r, StringComparer.Ordinal).First(),
});
_commsLatched.Remove(msg.DriverInstanceId);
ForgetCommsLatch(msg.DriverInstanceId);
}
/// <summary>
@@ -3574,6 +3629,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(
msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true, CatalogAttempt: _catalogAttempt,
ArtifactRevision: ArtifactRevisionOf(appliedBlob)));
// #1113 item 4: after the rebuild Tell, so it is replayed onto the nodes this apply (re)creates.
StampStubbedDriverValueNodes();
// Reaching here means the artifact came from central, so the node is no longer serving a
// cache-sourced configuration. Note this only clears on a real apply: a dispatch of the
// revision already booted from cache short-circuits in HandleDispatchFromSteady without
@@ -4279,6 +4336,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
CacheAppliedArtifact(deploymentId, rev, appliedBlob);
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, appliedBlob, CatalogAttempt: _catalogAttempt,
ArtifactRevision: ArtifactRevisionOf(appliedBlob)));
if (appliedBlob is not null) StampStubbedDriverValueNodes();
_log.Info("DriverHost {Node}: restored served state for applied deployment {Id} on bootstrap", _localNode, deploymentId);
}
catch (Exception ex)
@@ -4503,6 +4561,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_dataWriteRuntime.Routes.ReplaceRoutes(mapped);
}
// #1113 item 2: no comms latch may outlive the ref it names (a respawn's kept latch, or a kept driver's dropped ref).
TrimCommsLatchesToIndex();
// Gitea #979 (review 2026-12-02 R-6): a value ref that left the composition (raw tag deleted or renamed, or its
// driver removed) used to be only forgotten — a surviving VirtualTag / Calculation tag / scripted alarm that
// still reads it kept computing Good from its last value. Tell the mux, which hands every dependent naming it
@@ -5253,7 +5314,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// behind, a removed-while-comms-lost driver kept its whole RawPath set forever, a removal within the audit
// window still fired a false Warning + otopcua.driver.comms_latched_refs increment, and a disable ->
// re-enable of the same id inherited the stale latch.
_commsLatched.Remove(driverInstanceId);
// #1113 item 2: EXCEPT on a config-change respawn — like an operator Restart (#1053), the replacement is what
// must re-publish those refs, so the latch is kept for its Connected to audit. This apply's reindex trims it to
// the refs the new composition still carries (TrimCommsLatchesToIndex), so a dropped ref is never reported.
// The old incarnation's armed audit is cancelled either way.
if (!respawning) ForgetCommsLatch(driverInstanceId);
Timers.Cancel(CommsAuditTimerKey(driverInstanceId));
_healthPublisher.Forget(driverInstanceId);
_log.Info("DriverHost {Node}: stopped driver child {Id}", _localNode, driverInstanceId);
@@ -5350,11 +5415,60 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
if (writes.Count == 0) return;
_opcUaPublishActor.Tell(new OpcUa.OpcUaPublishActor.AttributeStatusBatchUpdate(writes));
// #1113 item 3: an outstanding comms latch now names nodes carrying THIS status, not BadNoCommunication.
if (_commsLatched.ContainsKey(driverInstanceId)) _commsLatchReplaced.Add(driverInstanceId);
_log.Info(
"DriverHost {Node}: driver {Driver} object replaced — {Count} value node(s) marked BadWaitingForInitialData until its first value",
_localNode, driverInstanceId, writes.Count);
}
/// <summary>
/// Gitea #1113 item 4 — stamps <see cref="OpcUaStatus.BadConfigurationError"/> on every raw NodeId and every
/// referencing UNS NodeId of each STUBBED child (or only <paramref name="onlyDriverInstanceId"/>): a stub (no
/// factory for the type, a factory that rejected the config, or a type not allowed on this node's roles) never
/// publishes, so its nodes would otherwise sit at <see cref="OpcUaStatus.BadWaitingForInitialData"/> forever —
/// a promise of a first value that cannot come.
/// </summary>
/// <remarks>
/// <para>
/// Called after each apply's <see cref="OpcUa.OpcUaPublishActor.RebuildAddressSpace"/> Tell (deploy, boot from
/// cache, bootstrap restore) on the same host→publish-actor pair, so the publish actor has already started
/// that plan: the write lands on the nodes that exist now AND is deferred and replayed onto the nodes the apply
/// creates or recreates (a fresh deploy, a rebuild) — re-sent every apply because a rebuild resets them. And
/// after an operator Restart that respawned a stub. A config-change respawn into a stub gets the respawn's
/// <c>BadWaitingForInitialData</c> first (at the stop), then this.
/// </para>
/// <para>
/// Status-only and not a comms loss: nothing is latched. A latch the previous incarnation left (a respawn
/// of a comms-lost driver, #1113 item 2) is dropped — a stub never connects, so its audit could never arm.
/// </para>
/// </remarks>
/// <param name="onlyDriverInstanceId">Restrict to this driver; <see langword="null"/> for every stubbed child.</param>
private void StampStubbedDriverValueNodes(string? onlyDriverInstanceId = null)
{
if (_opcUaPublishActor is null) return;
List<StatusWrite>? writes = null;
DateTime ts = default;
foreach (var (driverId, child) in _children)
{
if (!child.Stubbed) continue;
if (onlyDriverInstanceId is not null && !string.Equals(driverId, onlyDriverInstanceId, StringComparison.Ordinal)) continue;
ForgetCommsLatch(driverId);
if (!_valueRefsByDriver.TryGetValue(driverId, out var entries) || entries.Count == 0) continue;
if (writes is null) { writes = new List<StatusWrite>(); ts = DateTime.UtcNow; }
var before = writes.Count;
foreach (var (_, nodes) in entries)
foreach (var n in nodes)
writes.Add(new StatusWrite(n.NodeId, OpcUaStatus.BadConfigurationError, ts, n.Realm));
_log.Info(
"DriverHost {Node}: driver {Driver} ({Type}) is a stub on this node — {Count} value node(s) marked BadConfigurationError",
_localNode, driverId, child.DriverType, writes.Count - before);
}
if (writes is { Count: > 0 })
_opcUaPublishActor.Tell(new OpcUa.OpcUaPublishActor.AttributeStatusBatchUpdate(writes));
}
/// <summary>Marks a child this host is about to stop as retired and watches it until it terminates.</summary>
/// <param name="child">The child being stopped.</param>
private void RetireChild(IActorRef child)
@@ -5471,6 +5585,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// Respawn from the same spec the last reconcile used — preserves RowId, Name, ClusterId.
SpawnChild(entry.Spec);
// #1113 item 4: a stub replacement will never publish — not "waiting for initial data".
StampStubbedDriverValueNodes(msg.DriverInstanceId);
}
/// <summary>