fix(runtime): #1113 a config-change respawn keeps the comms latch, trimmed to the refs the new composition still routes

Item 2. StopChild cleared the comms-loss latch unconditionally, so a
config-change respawn of an already comms-lost driver never audited its
replacement (an operator Restart does, #1053). StopChild(respawning: true) now
keeps it; every apply's reindex trims every outstanding latch to the refs still
routed for that driver (TrimCommsLatchesToIndex) and drops an emptied one, so a
ref the deploy dropped (no longer subscribed, cannot be re-published) never
raises a false audit Warning. Both run inside the same apply message, before the
replacement's Connected can arm the audit.

Tests: DriverHostRespawnValueNodeGapTests — kept latch audits the silent
replacement for exactly the kept ref (fails if the latch is cleared or not
trimmed), and a replacement re-publishing every kept ref stays silent (fails
without the trim).
This commit is contained in:
Joseph Doherty
2026-12-05 03:03:43 -05:00
parent 5ef8089e1f
commit 77adf410df
3 changed files with 145 additions and 12 deletions
+8 -3
View File
@@ -594,9 +594,14 @@ 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. `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.
@@ -2364,7 +2364,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 +2384,40 @@ 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.</summary>
/// <param name="driverInstanceId">The driver whose latch ends.</param>
private void ForgetCommsLatch(string driverInstanceId)
{
_commsLatched.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,7 +2440,7 @@ 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;
}
@@ -2423,7 +2457,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_localNode, msg.DriverInstanceId, driverType, latched.Count, _commsRecoveryAuditDelay,
latched.OrderBy(r => r, StringComparer.Ordinal).First());
_commsLatched.Remove(msg.DriverInstanceId);
ForgetCommsLatch(msg.DriverInstanceId);
}
/// <summary>
@@ -4503,6 +4537,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 +5290,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);
@@ -151,11 +151,92 @@ 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 item 2: a config-change respawn 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).
/// </summary>
[Fact]
public void A_config_change_respawn_of_a_comms_lost_driver_audits_the_replacement_for_the_kept_refs_only()
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedV3Deployment(db, RevA,
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 BadNoCommunication").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>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 +248,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);