Merge #1002: StopChild clears comms latch + timer, kept alarm marks replayed, recorder catch-up uncapped, HistoryRead bad interval refused, VirtualTag host re-applied after restart, EffectiveName everywhere

This commit is contained in:
Joseph Doherty
2026-12-03 11:08:24 -05:00
22 changed files with 504 additions and 29 deletions
@@ -226,7 +226,7 @@ public static class DataConnectionValidator
"RawTagGroup" => draft.TagGroups.Any(x => Same(x.ParentTagGroupId, m.LocalParentId) && Name(x.Name)) || draft.Tags.Any(x => Same(x.TagGroupId, m.LocalParentId) && Name(x.Name)),
"UnsArea" => draft.UnsLines.Any(x => Same(x.UnsAreaId, m.LocalParentId) && Name(x.Name)),
"UnsLine" => draft.Equipment.Any(x => Same(x.UnsLineId, m.LocalParentId) && Name(x.Name)),
"Equipment" => draft.VirtualTags.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.ScriptedAlarms.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.UnsTagReferences.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.DisplayNameOverride ?? draft.Tags.FirstOrDefault(t => Same(t.TagId, x.TagId))?.Name)),
"Equipment" => draft.VirtualTags.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.ScriptedAlarms.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.UnsTagReferences.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(EquipmentReferenceMap.EffectiveName(x.DisplayNameOverride, draft.Tags.FirstOrDefault(t => Same(t.TagId, x.TagId))?.Name))),
_ => false
};
}
@@ -16,6 +16,20 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// </summary>
internal abstract record HistoryReadVariant
{
/// <summary>
/// U-7: whether a client's raw <c>ProcessingInterval</c> (a <see cref="double"/> of milliseconds) converts to a
/// <see cref="TimeSpan"/>. <c>TimeSpan.FromMilliseconds</c> throws for NaN and for infinity / magnitudes past ~9.2e14 ms,
/// and nothing between the SDK dispatcher and the node manager catches it — one bad value faulted the whole request.
/// </summary>
/// <param name="milliseconds">The wire value.</param>
/// <returns>True when <see cref="From"/> / the remote mapping will not throw.</returns>
public static bool IsConvertibleProcessingInterval(double milliseconds)
{
if (!double.IsFinite(milliseconds)) return false;
try { _ = TimeSpan.FromMilliseconds(milliseconds); return true; }
catch (Exception ex) when (ex is OverflowException or ArgumentException) { return false; }
}
/// <summary>Maps the SDK's <see cref="HistoryReadDetails"/> onto the port variant the overrides serve.</summary>
/// <param name="details">Raw/modified, Processed or AtTime details.</param>
/// <returns>The equivalent variant.</returns>
@@ -35,6 +35,15 @@ public sealed partial class OtOpcUaNodeManager
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors)
{
// U-7: an unconvertible ProcessingInterval (NaN / infinity / beyond TimeSpan) is the client's invalid argument,
// answered per node — never an exception out of the conversion below that faults the whole request.
if (details is ReadProcessedDetails { ProcessingInterval: var interval }
&& !HistoryReadVariant.IsConvertibleProcessingInterval(interval))
{
foreach (var handle in nodesToProcess) SetProjectedStatus(handle, results, errors, StatusCodes.BadInvalidArgument);
return;
}
List<NodeHandle>? projected = null;
foreach (var handle in nodesToProcess)
if (IsProjectedDescendant(handle.NodeId)) (projected ??= []).Add(handle);
@@ -53,7 +53,7 @@ public sealed partial class LocalExportCatalog
var tagById = tags.ToDictionary(x => x.TagId, ids);
var deviceById = devices.ToDictionary(x => x.DeviceId, ids);
var driverById = drivers.ToDictionary(x => x.DriverInstanceId, ids);
var referenceNames = references.Select(x => (x.EquipmentId, x.TagId, EffectiveName: x.DisplayNameOverride ?? tagById[x.TagId].Name)).ToArray();
var referenceNames = references.Select(x => (x.EquipmentId, x.TagId, EffectiveName: EquipmentReferenceMap.EffectiveName(x.DisplayNameOverride, tagById[x.TagId].Name)!)).ToArray();
var scopeResolver = new AclScopePathResolver(
folders.ToDictionary(x => x.RawFolderId, x => (x.ParentRawFolderId, x.Name), ids),
drivers.ToDictionary(x => x.DriverInstanceId, x => (x.RawFolderId, x.Name), ids),
@@ -56,6 +56,9 @@ public sealed class SourceSamplePublisher
private readonly object _gate = new();
private readonly Dictionary<BackingSourceKey, SourceTicket> _tickets = new();
private readonly Dictionary<(string Driver, string Reference), BackingSourceKey> _drivers = new();
// R-25: per-driver view of _drivers (reference -> key), so RetireDriver / PublishDriverStatus walk one driver's refs
// instead of scanning every bound ref of every driver under _gate. Always mutated beside _drivers.
private readonly Dictionary<string, Dictionary<string, BackingSourceKey>> _driverKeys = new(StringComparer.Ordinal);
private readonly Dictionary<string, BackingSourceKey> _virtuals = new(StringComparer.Ordinal);
internal sealed class SourceSlot
{
@@ -125,6 +128,9 @@ public sealed class SourceSamplePublisher
if (SourceKey.TryDriver(key, out driver, out reference))
{
_drivers[(driver, reference)] = key;
if (!_driverKeys.TryGetValue(driver, out var perDriver))
_driverKeys[driver] = perDriver = new Dictionary<string, BackingSourceKey>(StringComparer.Ordinal);
perDriver[reference] = key;
_driverRoutes[(driver, reference)] = binding;
}
else if (key.SourceKind == "virtual")
@@ -217,6 +223,9 @@ public sealed class SourceSamplePublisher
}
finally { Monitor.Exit(_gate); }
}
/// <summary>A snapshot of <paramref name="driver"/>'s bound source keys. Caller holds <c>_gate</c>.</summary>
private BackingSourceKey[] DriverKeys(string driver) =>
_driverKeys.TryGetValue(driver, out var perDriver) ? [.. perDriver.Values] : [];
public void RetireDriver(string driver, long incarnation)
{
// The hub sees the same fence. Reads and snapshots are denied before the slow per-tag walk.
@@ -226,14 +235,14 @@ public sealed class SourceSamplePublisher
{
if (!_driverIncarnations.TryGetValue(driver, out var current) || !ReferenceEquals(current, producer)) return;
_driverIncarnations.TryRemove(driver, out _);
foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray())
foreach (var key in DriverKeys(driver))
if (_tickets.TryGetValue(key, out var ticket)) TryRemove(ticket);
}
}
public void PublishDriverStatus(string driver, uint status)
{
lock (_gate)
foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray())
foreach (var key in DriverKeys(driver))
if (_tickets.TryGetValue(key, out var ticket)) TryPublishStatus(ticket, status, out _);
}
public bool TryCaptureVirtual(string id, out SourceTicket ticket)
@@ -598,7 +607,11 @@ public sealed class SourceSamplePublisher
_slots.TryRemove(ticket.Key, out _);
_tickets.Remove(ticket.Key);
if (SourceKey.TryDriver(ticket.Key, out var driver, out var reference))
{ _drivers.Remove((driver, reference)); _driverRoutes.TryRemove((driver, reference), out _); }
{
_drivers.Remove((driver, reference)); _driverRoutes.TryRemove((driver, reference), out _);
if (_driverKeys.TryGetValue(driver, out var perDriver) && perDriver.Remove(reference) && perDriver.Count == 0)
_driverKeys.Remove(driver);
}
else if (ticket.Key.SourceKind == "virtual")
{ _virtuals.Remove(ticket.Key.StableSourceId); _virtualRoutes.TryRemove(ticket.Key.StableSourceId, out _); }
if (_hub.TryRemove(ticket, checked(++slot.Sequence))) return true;
@@ -26,13 +26,16 @@ public sealed record ChildHealthRecord(
/// <remarks>
/// Deliberately NOT a message to the host: the children already publish through this seam on every
/// change, so a parallel <c>Tell</c> would double every health transition's traffic for one consumer.
/// Entries are removed by the host when it stops a child; a late publish from a stopping child may re-add
/// one, which the host filters against its live child set when it answers.
/// Entries are removed by the host when it stops a child, and the id is then held (like the telemetry hub's
/// tombstone) so a late publish from the stopping child is not re-recorded; a later spawn of the same id lifts
/// the hold via <see cref="Readmit"/>.
/// </remarks>
public sealed class ChildHealthLedger : IDriverHealthPublisher
{
private readonly IDriverHealthPublisher _inner;
private readonly ConcurrentDictionary<string, ChildHealthRecord> _last = new(StringComparer.Ordinal);
// Ids whose child was stopped: a late publish from the stopping child must not resurrect the entry (R-16).
private readonly ConcurrentDictionary<string, byte> _held = new(StringComparer.Ordinal);
/// <summary>Wraps <paramref name="inner"/>.</summary>
/// <param name="inner">The publisher every snapshot is forwarded to.</param>
@@ -54,8 +57,9 @@ public sealed class ChildHealthLedger : IDriverHealthPublisher
SkippedTagReport? skippedTags = null,
IReadOnlyDictionary<string, string>? diagnostics = null)
{
_last[driverInstanceId] = new ChildHealthRecord(
health.State, health.LastSuccessfulRead, health.LastError, hostStatuses, DateTime.UtcNow);
if (!_held.ContainsKey(driverInstanceId))
_last[driverInstanceId] = new ChildHealthRecord(
health.State, health.LastSuccessfulRead, health.LastError, hostStatuses, DateTime.UtcNow);
_inner.Publish(
clusterId, driverInstanceId, health, errorCount5Min, rediscoveryNeededUtc, rediscoveryReason,
hostStatuses, skippedTags, diagnostics);
@@ -67,7 +71,18 @@ public sealed class ChildHealthLedger : IDriverHealthPublisher
public ChildHealthRecord? TryGet(string driverInstanceId) =>
_last.TryGetValue(driverInstanceId, out var record) ? record : null;
/// <summary>Forgets <paramref name="driverInstanceId"/>'s snapshot (the child was stopped).</summary>
/// <summary>
/// Forgets <paramref name="driverInstanceId"/>'s snapshot (the child was stopped) and HOLDS the id: a late
/// publish from the stopping child is forwarded but no longer recorded, until <see cref="Readmit"/>.
/// </summary>
/// <param name="driverInstanceId">The driver instance.</param>
public void Forget(string driverInstanceId) => _last.TryRemove(driverInstanceId, out _);
public void Forget(string driverInstanceId)
{
_held[driverInstanceId] = 0;
_last.TryRemove(driverInstanceId, out _);
}
/// <summary>Lifts the hold <see cref="Forget"/> placed, because a new child of the id is being spawned.</summary>
/// <param name="driverInstanceId">The driver instance.</param>
public void Readmit(string driverInstanceId) => _held.TryRemove(driverInstanceId, out _);
}
@@ -331,6 +331,10 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// first apply.</summary>
private IReadOnlyList<EquipmentScriptedAlarmPlan>? _lastScriptedAlarmPlans;
/// <summary>The VirtualTag plans last sent to <see cref="_virtualTagHost"/>, re-sent when it reports a supervision
/// restart (<see cref="VirtualTagHostActor.VirtualTagHostRestarted"/>). Null until the first apply.</summary>
private IReadOnlyList<EquipmentVirtualTagPlan>? _lastVirtualTagPlans;
private RevisionHash? _currentRevision;
/// <summary>
@@ -1841,6 +1845,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
Receive<DrainProjectedRetirements>(RetireProjected);
Receive<Terminated>(OnRetiredChildTerminated);
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
Receive<VirtualTagHostActor.VirtualTagHostRestarted>(_ => HandleVirtualTagHostRestarted());
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
Receive<DriverInstanceActor.ConnectivityChanged>(OnDriverConnectivityChanged);
ReceiveConditionSignals();
@@ -1923,6 +1928,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
Receive<DrainProjectedRetirements>(RetireProjected);
Receive<Terminated>(OnRetiredChildTerminated);
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
Receive<VirtualTagHostActor.VirtualTagHostRestarted>(_ => HandleVirtualTagHostRestarted());
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
Receive<DriverInstanceActor.ConnectivityChanged>(OnDriverConnectivityChanged);
ReceiveConditionSignals();
@@ -3057,6 +3063,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_localNode, m.Items.Count, m.DriverInstanceId));
Receive<Terminated>(OnRetiredChildTerminated);
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
Receive<VirtualTagHostActor.VirtualTagHostRestarted>(_ => HandleVirtualTagHostRestarted());
Receive<DriverInstanceActor.AttributeAlarmPublished>(m =>
_log.Debug("DriverHost {Node}: dropping a native alarm transition ({Cond}) from {Id} while Stale",
_localNode, m.Args.ConditionId, m.DriverInstanceId));
@@ -4324,6 +4331,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// deployment dispatch. This is intentional and consistent with driver recovery: the Stale
// path only restores the revision marker + NodeDeploymentState; a subsequent dispatch
// (or a redeploy from AdminUI) triggers the full apply + subscribe pass.
_lastVirtualTagPlans = composition.EquipmentVirtualTags;
_virtualTagHost?.Tell(new VirtualTagHostActor.ApplyVirtualTags(composition.EquipmentVirtualTags));
if (composition.EquipmentVirtualTags.Count > 0)
{
@@ -4698,6 +4706,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// items) may come back; lift the hold BEFORE the child exists, since it publishes health as it starts.
// The resilience tracker's equivalent is lifted by _invokerFactory.Create below.
_telemetryHub?.Readmit(spec.DriverInstanceId);
_healthPublisher.Readmit(spec.DriverInstanceId);
var stub = DriverInstanceActor.ShouldStub(spec.DriverType, _localRoles);
IDriver? driver = null;
if (!stub)
@@ -4875,6 +4884,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// backoff it never earned (its first crash was deferred as a "crash loop").
_lastReprovisionUtc.Remove(driverInstanceId);
Timers.Cancel(ReprovisionTimerKey(driverInstanceId));
// R-16: the comms-loss latch and its recovery-audit timer belong to the incarnation that just ended. Left
// 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);
Timers.Cancel(CommsAuditTimerKey(driverInstanceId));
_healthPublisher.Forget(driverInstanceId);
_log.Info("DriverHost {Node}: stopped driver child {Id}", _localNode, driverInstanceId);
}
@@ -4927,6 +4942,23 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_scriptedAlarmHost.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(_lastScriptedAlarmPlans));
}
/// <summary>
/// The VirtualTag host was restarted by supervision and has no children: re-send the last plans so every
/// VirtualTag evaluates again without waiting for the next deploy. Only the CURRENT host's signal is honoured.
/// </summary>
private void HandleVirtualTagHostRestarted()
{
if (_virtualTagHost is null || !Sender.Equals(_virtualTagHost)) return;
if (_lastVirtualTagPlans is null)
{
_log.Debug("DriverHost {Node}: VirtualTag host restarted before any apply; nothing to re-send", _localNode);
return;
}
_log.Warning("DriverHost {Node}: VirtualTag host was restarted by supervision; re-applying {Count} virtual tag(s)",
_localNode, _lastVirtualTagPlans.Count);
_virtualTagHost.Tell(new VirtualTagHostActor.ApplyVirtualTags(_lastVirtualTagPlans));
}
/// <summary>A retired child has terminated; nothing more can arrive from it.</summary>
/// <param name="msg">The termination notice.</param>
private void OnRetiredChildTerminated(Terminated msg) => _retiredChildren.Remove(msg.ActorRef);
@@ -1057,6 +1057,10 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
_currentBackoff = _minBackoff;
_nextAllowedDrainUtc = DateTime.MinValue;
Timers.StartSingleTimer(DrainTimerKey, DrainTick.Instance, _drainInterval);
// R-25: a FULL acked batch means more is probably waiting (an outage backlog). Re-tick now rather than
// waiting out the interval, which capped catch-up at drainBatchSize / drainInterval (~512 entries/s by
// default — ~33 min for a 1M-entry backlog). A short batch (queue drained) falls back to the steady cadence.
if (!_stopping && result.Acked >= _drainBatchSize) Self.Tell(DrainTick.Instance);
return;
}
@@ -257,7 +257,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
bool AllVariables,
IReadOnlySet<(AddressSpaceRealm, string)> Variables,
IReadOnlyDictionary<(AddressSpaceRealm, string), VariableShape> Reshaped,
IReadOnlySet<(AddressSpaceRealm, string)> Conditions)
IReadOnlySet<(AddressSpaceRealm, string)> Conditions,
IReadOnlySet<(AddressSpaceRealm, string)>? ExistingConditions = null)
{
private static readonly IReadOnlySet<(AddressSpaceRealm, string)> None = new HashSet<(AddressSpaceRealm, string)>();
public static readonly ReplayScope Nothing =
@@ -1189,11 +1190,17 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying {Count} deferred status writes threw", statuses.Count); }
}
// G3 pre-pass: a deferred projection outside the applied scope is skipped — its source's KNOWN marks are discarded
// wherever they sit in the arrival order (the conservative reading of "never known over a projection that did
// not land").
// G3 pre-pass: a deferred projection of a condition that exists in NEITHER the previous nor the applied
// composition never landed anywhere — its source's KNOWN marks are discarded wherever they sit in the arrival
// order (the conservative reading of "never known over a projection that did not land"). R-18: a projection
// outside the replay scope for a condition that DOES exist (a kept condition on a surgical / no-artifact apply,
// or a removed one) is not a loss — the live write already landed on the surviving node, or there is no node.
foreach (var (alarm, _) in _deferred.Alarms)
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) _deferred.NoteAlarmLoss(alarm.Source);
{
var key = (alarm.Realm, alarm.AlarmNodeId);
if (!scope.Conditions.Contains(key) && scope.ExistingConditions?.Contains(key) != true)
_deferred.NoteAlarmLoss(alarm.Source);
}
// #926 review r2: alarm states, alarm qualities and condition-known marks replay as ONE list in ARRIVAL order.
// Marks used to replay after every alarm, which was right for a "known" mark (it summarises the projections
@@ -1523,7 +1530,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
if (a.Enabled) conditions.Add((AddressSpaceRealm.Uns, a.ScriptedAlarmId));
}
_replayScope = new ReplayScope(rebuilt, recording.Ensured, recording.Reshaped, conditions);
var existing = ConditionIds(previous);
existing.UnionWith(ConditionIds(ready.Composition));
_replayScope = new ReplayScope(rebuilt, recording.Ensured, recording.Reshaped, conditions, existing);
return result;
}
finally
@@ -1540,16 +1549,17 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
var added = ConditionIds(next);
added.ExceptWith(ConditionIds(previous));
return added;
}
static HashSet<(AddressSpaceRealm, string)> ConditionIds(AddressSpaceComposition c)
{
var ids = new HashSet<(AddressSpaceRealm, string)>();
foreach (var a in c.EquipmentScriptedAlarms)
if (a.Enabled) ids.Add((AddressSpaceRealm.Uns, a.ScriptedAlarmId));
foreach (var t in c.RawTags)
if (t.Alarm is not null) ids.Add((AddressSpaceRealm.Raw, t.NodeId));
return ids;
}
/// <summary>Every condition id a composition materialises: enabled scripted alarms (Uns) and native alarms (Raw).</summary>
private static HashSet<(AddressSpaceRealm, string)> ConditionIds(AddressSpaceComposition c)
{
var ids = new HashSet<(AddressSpaceRealm, string)>();
foreach (var a in c.EquipmentScriptedAlarms)
if (a.Enabled) ids.Add((AddressSpaceRealm.Uns, a.ScriptedAlarmId));
foreach (var t in c.RawTags)
if (t.Alarm is not null) ids.Add((AddressSpaceRealm.Raw, t.NodeId));
return ids;
}
private (bool Degraded, string? Reason) ApplyPlanCore(PlanReady ready, out bool rebuilt)
@@ -47,6 +47,21 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
/// <param name="Plans">The desired Equipment-namespace VirtualTag plans.</param>
public sealed record ApplyVirtualTags(IReadOnlyList<EquipmentVirtualTagPlan> Plans);
/// <summary>
/// Told to the parent from <see cref="PostRestart"/> (mirrors <c>ScriptedAlarmHostActor.ScriptedAlarmHostRestarted</c>).
/// A supervision restart is otherwise invisible to the parent and the new incarnation has NO children (Akka's
/// default <c>PreRestart</c> stops them) and no definitions, so every VirtualTag on the node would stop
/// evaluating until the next deploy. The parent (<c>DriverHostActor</c>) answers by re-sending the last
/// <see cref="ApplyVirtualTags"/> it sent.
/// </summary>
public sealed class VirtualTagHostRestarted
{
/// <summary>The single instance.</summary>
public static readonly VirtualTagHostRestarted Instance = new();
private VirtualTagHostRestarted() { }
}
private readonly IActorRef? _publishActor;
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
private readonly HashSet<string> _publishedVirtualIds = new(StringComparer.Ordinal);
@@ -113,6 +128,14 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
Receive<Terminated>(OnChildTerminated);
}
/// <inheritdoc />
/// <remarks>Tells the parent <see cref="VirtualTagHostRestarted"/> so it re-sends the last <see cref="ApplyVirtualTags"/>.</remarks>
protected override void PostRestart(Exception reason)
{
base.PostRestart(reason);
Context.Parent.Tell(VirtualTagHostRestarted.Instance);
}
private void OnApply(ApplyVirtualTags msg)
{
Timers.Cancel("source-binding-retry");