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
+6
View File
@@ -154,6 +154,12 @@ non-`Healthy` state **and** its `LastSuccessfulRead` has been frozen for 90 s. T
an outage: no audit, no counter), and the retired child's late Bad no longer stamps value nodes while a replacement
exists — so a Restart now cancels the old audit itself (#1053 keeps the latch). Supervision restarts and deploy
removals/disables are unchanged. ScadaBridge sees the brief Bad. `DriverHostRespawnValueNodeGapTests`.
#1113: a config-change respawn KEEPS an outstanding comms latch like Restart, and every apply trims latches to the
refs still routed (`TrimCommsLatchesToIndex` — a dropped ref is never audited); the audit Warning names the nodes'
real status (`still BadWaitingForInitialData` after a respawn/Restart). A STUB child's value nodes go
`BadConfigurationError` (`StampStubbedDriverValueNodes`, after each apply's rebuild Tell + after a Restart into a
stub). A slow-connecting replacement stays `BadWaitingForInitialData` (accepted). The gRPC origin hub is covered by
the producer fence (`RetireCurrentDriver` at the stop), not the node stamp — `GrpcDataRespawnOriginGapTests`.
- **Every dedup on the recovery path is keyed on (value, status), not value.** A device that comes back
usually comes back holding the same reading, so a value-only dedup swallows the recovery and the node
stays Bad forever — the v3-gate trap, now closed in the Calculation driver, the virtual-tag actor and
+32 -3
View File
@@ -594,9 +594,16 @@ latched Bad, as a Warning naming the driver plus the `otopcua.driver.comms_latch
a push driver missing its initial push, or a value-only dedup swallowing an unchanged value. It is a
tripwire, not a repair: nothing downstream depends on it.
The latch and its audit timer belong to one driver incarnation: `StopChild` (a deploy removal, a disable, the stop half of
a config-change respawn) drops the latch and cancels the pending audit (R-16), so a removed driver never fires a false
Warning / counter increment and a disable then re-enable of the same id never inherits a stale latch. `StopChild` also
The latch and its audit timer belong to one driver incarnation: `StopChild` for a deploy removal or a disable drops the
latch and cancels the pending audit (R-16), so a removed driver never fires a false Warning / counter increment and a
disable then re-enable of the same id never inherits a stale latch. The stop half of a **config-change respawn** keeps it
instead (#1113 — it used to drop it, so a respawn of an already comms-lost driver was never audited, unlike a Restart):
the replacement is what must re-publish those refs. Every apply's reindex trims every outstanding latch to the refs the new
composition still routes for that driver (`TrimCommsLatchesToIndex`) — a ref the deploy dropped is no longer subscribed and
can never be re-published, so it must not be reported — and drops a latch left empty; this runs inside the same apply
message as the respawn, so before the replacement's `Connected` can arm the audit. The Warning names the status the nodes
actually carry: `still BadNoCommunication`, or `still BadWaitingForInitialData` once a respawn / Restart re-stamped them
(#1113). A stub replacement drops the latch (it never connects, so the audit could never arm). `StopChild` also
holds the id in the `ChildHealthLedger` (`Forget` then `Readmit` on the next spawn), so the stopped child's late health
publish cannot resurrect its diagnostics entry.
@@ -642,6 +649,28 @@ supervision restart (same driver object — unchanged, still covered by that chi
disable (`RemovedInputStatus` + node removal). ScadaBridge sees a brief Bad per respawn/Restart — accepted.
Pinned by `DriverHostRespawnValueNodeGapTests` (both seams, both interleavings, no-latch with a positive control).
- **A slow-connecting replacement reads `BadWaitingForInitialData`, not `BadNoCommunication` — accepted (#1113, owner
decision).** The stamp says "a new driver object, no value yet"; it does not change while the replacement's initialise is
still retrying, because the replacement has not lost anything — it has not connected yet. The nodes go
`BadNoCommunication` only if the replacement connects and then loses its device (its own comms-loss stamp, latched and
audited as usual). An operator watching a node stuck at `BadWaitingForInitialData` after a respawn should check the
driver's status on `/hosts` (Connecting / Reconnecting), not the node.
- **A stub replacement reads `BadConfigurationError` (#1113).** When the replacement (or a freshly deployed driver) is a
STUB — no factory for its type on this node, the factory rejected its config, or the type is not allowed on the node's
roles — it never publishes, so `BadWaitingForInitialData` would be a promise that cannot be kept.
`StampStubbedDriverValueNodes` stamps `BadConfigurationError` on the raw + UNS value nodes of every stubbed child after
each apply's `RebuildAddressSpace` Tell (deploy, boot-from-cache, bootstrap restore — on the same host→publish-actor pair,
so the publish actor defers it behind that plan and replays it onto the nodes the apply creates or recreates; re-sent every
apply because a rebuild resets them) and after an operator Restart that respawned a stub. Status-only, not latched.
- **The gRPC data plane's origin side is covered by the producer fence, not by this stamp (#1113).** Projected consumers
(DataConnectionService read / subscribe) do not read the OPC UA node state: they read the `PartitionedSampleHub`, fed
by the driver callback through `SourceSamplePublisher`. `StopChild` / `HandleRestartDriver` call
`RetireCurrentDriver` at the stop, which removes every one of the driver's sources (cached sample released, readiness
`Invalidated`), and spawning the replacement registers a new incarnation (retiring the old fence a second time). Until the
replacement's first value binds a fresh generation there is no current source — a read answers `WaitingForInitialData`,
the old ticket reads not-ready — so the stopped object's last Good is never served there either. Pinned by
`GrpcDataRespawnOriginGapTests` (both seams).
### The connect path feeds the circuit breaker (R2-10 T10 closure)
`IDriver.InitializeAsync` is routed through the capability invoker as
@@ -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>
@@ -192,12 +192,13 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase
driver.InitializeGate = release.Task;
host.Tell(new RestartDriver("c1", "drv-restart", "test-operator", Guid.NewGuid()));
EventFilter.Warning(contains: "still BadNoCommunication")
EventFilter.Warning(contains: "ref(s) still")
.Expect(0, audit + TimeSpan.FromSeconds(3), () => { }, TestContext.Current.CancellationToken);
meter.SumWithTag("driver_instance", "drv-restart").ShouldBe(0);
// The new incarnation connects, re-subscribes silently, and its own audit reports the ref the restart kept.
EventFilter.Warning(contains: "still BadNoCommunication").ExpectOne(audit + ReconnectBudget, () =>
// The new incarnation connects, re-subscribes silently, and its own audit reports the ref the restart kept —
// naming the status the Restart re-stamped (#1112), not BadNoCommunication (#1113 item 3).
EventFilter.Warning(contains: "1 ref(s) still BadWaitingForInitialData").ExpectOne(audit + ReconnectBudget, () =>
{
driver.InitializeGate = null;
release.SetResult();
@@ -138,7 +138,7 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
// flow never re-published. Had the respawn latched it, the audit armed by the replacement's Connected would
// report it after AuditDelay.
EventFilter.Warning(contains: "still BadNoCommunication")
EventFilter.Warning(contains: "ref(s) still")
.Expect(0, AuditDelay + TimeSpan.FromSeconds(2), () => { }, TestContext.Current.CancellationToken);
meter.SumWithTag("driver_instance", DriverId).ShouldBe(0);
@@ -151,11 +151,162 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
TestContext.Current.CancellationToken);
}
private (IActorRef Host, TestProbe Publish, TestProbe Coordinator, Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> Db)
Arrange(GatedDriver oldDriver, GatedDriver newDriver)
// ---- #1113 items 2 + 3: a respawn / Restart of a driver that was ALREADY comms-lost ----
/// <summary>Long enough that a test can fire the replacement's first value before the audit runs.</summary>
private static readonly TimeSpan LongAuditDelay = TimeSpan.FromSeconds(3);
/// <summary>
/// #1113 item 2: a config-change respawn of a comms-lost driver KEEPS the latch (it used to be cleared, so the
/// replacement was never audited — unlike an operator Restart, #1053), trimmed to the refs the new composition
/// still carries. The new deployment drops <c>flow</c> and adds <c>temp</c>; the silent replacement is reported
/// for exactly <c>speed</c> — not <c>flow</c> (dropped: a false warning) and not <c>temp</c> (never latched).
/// Item 3: the warning names the status the nodes carry, <c>BadWaitingForInitialData</c>.
/// </summary>
[Fact]
public void A_config_change_respawn_of_a_comms_lost_driver_audits_the_replacement_for_the_kept_refs_only()
{
var oldDriver = new GatedDriver(DriverId);
var newDriver = new GatedDriver(DriverId);
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver, LongAuditDelay);
SeedGoodFromOldDriver(oldDriver, publish);
using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs");
GoCommsLost(oldDriver, host, publish);
EventFilter.Warning(contains: "1 ref(s) still BadWaitingForInitialData").ExpectOne(
LongAuditDelay + PresenceBudget,
() => DispatchDroppingFlow(host, coordinator, db),
TestContext.Current.CancellationToken);
AwaitCondition(() => meter.SumWithTag("driver_instance", DriverId) == 1, TimeSpan.FromSeconds(5),
TestContext.Current.CancellationToken);
}
/// <summary>
/// #1113 item 2, the other half: when the replacement re-publishes every KEPT ref, the audit is silent — the
/// dropped <c>flow</c> (no longer subscribed, so it can never be re-published) is trimmed from the latch.
/// Without the trim this reported <c>flow</c>; without the kept latch the test above stays silent.
/// </summary>
[Fact]
public void A_ref_dropped_by_the_respawning_deploy_never_raises_a_false_audit_warning()
{
var oldDriver = new GatedDriver(DriverId);
var newDriver = new GatedDriver(DriverId);
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver, LongAuditDelay);
SeedGoodFromOldDriver(oldDriver, publish);
using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs");
GoCommsLost(oldDriver, host, publish);
DispatchDroppingFlow(host, coordinator, db);
AwaitFinalSubscribe(newDriver, configChange: true);
newDriver.Fire(SpeedRef, 11.0);
EventFilter.Warning(contains: "ref(s) still")
.Expect(0, LongAuditDelay + TimeSpan.FromSeconds(2), () => { }, TestContext.Current.CancellationToken);
meter.SumWithTag("driver_instance", DriverId).ShouldBe(0);
}
/// <summary>
/// #1113 item 3: an operator Restart keeps the latch (#1053), but the Restart re-stamped the nodes
/// <c>BadWaitingForInitialData</c> (#1112) — so the audit must not claim they are "still BadNoCommunication".
/// </summary>
[Fact]
public void A_restart_of_a_comms_lost_driver_audit_names_the_awaiting_first_value_status()
{
var oldDriver = new GatedDriver(DriverId);
var newDriver = new GatedDriver(DriverId);
var (host, publish, _, _) = Arrange(oldDriver, newDriver, LongAuditDelay);
SeedGoodFromOldDriver(oldDriver, publish);
GoCommsLost(oldDriver, host, publish);
EventFilter.Warning(contains: "2 ref(s) still BadWaitingForInitialData").ExpectOne(
LongAuditDelay + PresenceBudget,
() => host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid())),
TestContext.Current.CancellationToken);
}
// ---- #1113 item 4: a stubbed replacement / a stub deploy ----
/// <summary>
/// #1113 item 4: when the replacement is a STUB (here: no factory for the type), its nodes would otherwise sit at
/// <c>BadWaitingForInitialData</c> forever. They go <c>BadConfigurationError</c>, after the respawn stamp — for a
/// config change after the apply's <c>RebuildAddressSpace</c> (so the publish actor replays it onto the nodes the
/// apply recreates), including the ref the new deployment adds.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void A_stubbed_replacement_marks_the_value_nodes_BadConfigurationError(bool configChange)
{
var oldDriver = new GatedDriver(DriverId);
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver: null);
SeedGoodFromOldDriver(oldDriver, publish);
Replace(configChange, host, coordinator, db);
var stamp = ExpectStampBeforeAnyValue(publish);
stamp.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadWaitingForInitialData);
var rebuildSeen = false;
var config = (OpcUaPublishActor.AttributeStatusBatchUpdate)publish.FishForMessage(m =>
{
if (m is OpcUaPublishActor.RebuildAddressSpace) rebuildSeen = true;
return m is OpcUaPublishActor.AttributeStatusBatchUpdate s
&& s.Items.Any(i => i.StatusCode == OpcUaStatus.BadConfigurationError);
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var expected = configChange ? AllOldNodes.Append(TempRef).ToArray() : AllOldNodes;
config.Items.Select(i => i.NodeId).ShouldBe(expected, ignoreOrder: true);
config.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadConfigurationError);
rebuildSeen.ShouldBe(configChange, "a config change stamps after its apply's rebuild; a Restart has none");
}
/// <summary>#1113 item 4 on a fresh deploy: a driver that is a stub from the start never gets a first value either —
/// its nodes are marked <c>BadConfigurationError</c> right after the apply's <c>RebuildAddressSpace</c>.</summary>
[Fact]
public void A_fresh_deploy_of_a_stub_marks_its_value_nodes_BadConfigurationError()
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedV3Deployment(db, RevA,
var deploymentId = SeedTwoTagDeployment(db);
var (_, publish, _, _) = SpawnHostAndApplyWithCoordinator(this, db, TestNode, deploymentId, RevA,
driverFactory: new SequenceDriverFactory(new IDriver?[] { null }));
// SpawnHostAndApplyWithCoordinator consumed the RebuildAddressSpace: the stamp is what follows it.
var config = publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
config.Items.Select(i => i.NodeId).ShouldBe(AllOldNodes, ignoreOrder: true);
config.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadConfigurationError);
}
/// <summary>Takes the old driver comms-lost (Force Reconnect with its re-initialise held forever) and waits for the
/// host's latched <c>BadNoCommunication</c> stamp.</summary>
private static void GoCommsLost(GatedDriver oldDriver, IActorRef host, TestProbe publish)
{
oldDriver.InitializeGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously).Task;
host.Tell(new ReconnectDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
var outage = publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(
s => s.Items.Any(i => i.NodeId == SpeedRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
outage.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadNoCommunication);
}
/// <summary>A config change that keeps <c>speed</c>, DROPS <c>flow</c> (and its UNS mirror) and adds <c>temp</c>.</summary>
private static void DispatchDroppingFlow(IActorRef host, TestProbe coordinator,
Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> db)
{
var revB = SeedV3Deployment(db, RevB,
rawTags:
[
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false),
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "temp", DataType: "Double", Writable: false),
],
unsRefs:
[
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null),
],
enabled: true);
Dispatch(host, coordinator, revB, RevB);
}
private static DeploymentId SeedTwoTagDeployment(
Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> db) =>
SeedV3Deployment(db, RevA,
rawTags:
[
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false),
@@ -167,8 +318,14 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "flow", Effective: (string?)null),
],
enabled: true);
private (IActorRef Host, TestProbe Publish, TestProbe Coordinator, Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> Db)
Arrange(GatedDriver oldDriver, GatedDriver? newDriver, TimeSpan? auditDelay = null)
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedTwoTagDeployment(db);
var (host, publish, _, coordinator) = SpawnHostAndApplyWithCoordinator(this, db, TestNode, deploymentId, RevA,
driverFactory: new SequenceDriverFactory(oldDriver, newDriver), commsRecoveryAuditDelay: AuditDelay);
driverFactory: new SequenceDriverFactory(oldDriver, newDriver), commsRecoveryAuditDelay: auditDelay ?? AuditDelay);
AwaitAssert(() => (oldDriver.LastSubscribedRefs ?? []).ShouldContain(SpeedRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
return (host, publish, coordinator, db);
@@ -245,8 +402,9 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
return (statuses, (OpcUaPublishActor.AttributeValueBatchUpdate)msg);
}
/// <summary>Hands out the given drivers in order, one per spawn (the last one repeats).</summary>
private sealed class SequenceDriverFactory(params IDriver[] drivers) : IDriverFactory
/// <summary>Hands out the given drivers in order, one per spawn (the last one repeats); a null is "no factory for
/// this type", which makes the host spawn a stub.</summary>
private sealed class SequenceDriverFactory(params IDriver?[] drivers) : IDriverFactory
{
private int _next;
@@ -0,0 +1,163 @@
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// <b>#1113 item 1 — the gRPC data plane's origin side across a driver-object change.</b> Projected consumers
/// (DataConnectionService read / subscribe) are NOT served from the OPC UA node state: they read the
/// <see cref="PartitionedSampleHub"/>, a value cache of its own that the driver's callback feeds through
/// <see cref="SourceSamplePublisher"/>. So #1112's node stamp does not reach them — this pins that they are covered
/// by the producer fence instead: <c>StopChild</c> / <c>HandleRestartDriver</c> call
/// <see cref="SourceSamplePublisher.RetireCurrentDriver"/> at the stop, which removes every one of the driver's
/// sources (cache released, readiness <see cref="DataReadiness.Invalidated"/>), and the replacement's first value
/// binds a fresh generation. Between the two, the stopped object's last Good is never served: there is no current
/// source (a read answers <see cref="DataItemStatus.WaitingForInitialData"/>) and the old ticket reads not-ready.
/// </summary>
[Trait("Feature", "GrpcData"), Trait("Category", "Unit")]
public sealed class GrpcDataRespawnOriginGapTests : RuntimeActorTestBase
{
private const string DriverId = "DI-1";
private const string SpeedRef = "Plant/Modbus/dev1/speed";
private const string TempRef = "Plant/Modbus/dev1/temp";
private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64));
private static readonly RevisionHash RevB = RevisionHash.Parse(new string('b', 64));
[Theory]
[InlineData(false)]
[InlineData(true)]
public void The_origin_hub_never_serves_the_stopped_drivers_last_Good_until_the_replacement_publishes(bool configChange)
{
var db = NewInMemoryDbFactory();
var deploy = V3ArtifactSeeder.SeedV3Deployment(db, RevA,
[(DriverId, "Modbus", "dev1", "speed", "Double", false)], [], enabled: true);
var oldDriver = new FiringDriver();
var newDriver = new FiringDriver();
var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
newDriver.InitializeGate = hold.Task;
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: new SequenceFactory(oldDriver, newDriver), localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher,
acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)));
V3ArtifactSeeder.Dispatch(host, coordinator, deploy, RevA);
AwaitAssert(() => oldDriver.Subscribed.ShouldContain(SpeedRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
// The old driver object's Good reaches the origin hub.
oldDriver.Fire(SpeedRef, 11.0);
SourceTicket oldTicket = default;
AwaitAssert(() =>
{
publisher.TryCaptureDriver(DriverId, SpeedRef, out oldTicket).ShouldBeTrue();
hub.ProcessPending();
using var read = hub.Read(oldTicket);
read.Readiness.ShouldBe(DataReadiness.Ready);
read.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(11.0);
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var key = oldTicket.Key;
if (configChange)
{
var revB = V3ArtifactSeeder.SeedV3Deployment(db, RevB,
[(DriverId, "Modbus", "dev1", "speed", "Double", false), (DriverId, "Modbus", "dev1", "temp", "Double", false)],
[], enabled: true);
V3ArtifactSeeder.Dispatch(host, coordinator, revB, RevB);
}
else host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
// The replacement cannot publish (its initialise is held): what a consumer sees now is the whole gap.
AwaitAssert(() =>
{
hub.ProcessPending();
using (var stale = hub.Read(oldTicket)) stale.Readiness.ShouldNotBe(DataReadiness.Ready);
if (hub.TryGetCurrentTicket(key, out var current))
{
using var read = hub.Read(current);
read.Readiness.ShouldNotBe(DataReadiness.Ready, "no current source may serve the stopped object's Good");
}
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
publisher.TryCaptureDriver(DriverId, SpeedRef, out _).ShouldBeFalse("the stopped producer's sources are retired");
// The replacement's first value — the IDENTICAL value — is what makes the origin Good again.
hold.SetResult();
AwaitAssert(() => newDriver.Subscribed.ShouldContain(configChange ? TempRef : SpeedRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
newDriver.Fire(SpeedRef, 11.0);
AwaitAssert(() =>
{
hub.ProcessPending();
hub.TryGetCurrentTicket(key, out var current).ShouldBeTrue();
current.ShouldNotBe(oldTicket);
using var read = hub.Read(current);
read.Readiness.ShouldBe(DataReadiness.Ready);
read.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(11.0);
read.Sample.StatusCode.ShouldBe(OpcUaStatus.Good);
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Hands out the given drivers in order, one per spawn (the last one repeats).</summary>
private sealed class SequenceFactory(params IDriver[] drivers) : IDriverFactory
{
private int _next;
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson) =>
drivers[Math.Min(Interlocked.Increment(ref _next) - 1, drivers.Length - 1)];
public IReadOnlyCollection<string> SupportedTypes { get; } = ["Modbus"];
}
/// <summary>A subscribable driver that publishes only when told to, and whose initialise can be held.</summary>
private sealed class FiringDriver : IDriver, ISubscribable
{
private readonly StubHandle _handle = new();
private readonly Lock _gate = new();
private IReadOnlyList<string> _subscribed = [];
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public Task? InitializeGate { get; set; }
public string DriverInstanceId => DriverId;
public string DriverType => "Modbus";
public IReadOnlyList<string> Subscribed
{
get { lock (_gate) return _subscribed; }
}
public void Fire(string fullReference, object value) =>
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, fullReference,
new DataValueSnapshot(value, OpcUaStatus.Good, DateTime.UtcNow, DateTime.UtcNow)));
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) =>
InitializeGate is { } gate ? gate.WaitAsync(cancellationToken) : Task.CompletedTask;
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
lock (_gate) _subscribed = fullReferences.ToArray();
return Task.FromResult<ISubscriptionHandle>(_handle);
}
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask;
}
}