fix(grpc-data): #926 review r2 - deferred alarms and marks replay in arrival order; stale-record guard; F5 count on withdraw

- OpcUaPublishActor: deferred alarm states, qualities and condition marks replay as one
  arrival-ordered list (a withdrawal followed by a re-establishing transition ended
  unknown); marks held per (realm, condition) so withdrawals are bounded by the condition set
- OpcUaClientDriver: signal/withdraw re-check the registration under _alarmStateLock;
  removals take the lock
- DriverHostActor: a withdrawal under a raised F5 diagnostic updates its count
- docs: Unsignalable/backstop residual; AlarmInitialStatePublished must stay in-process
- tests: arrival-order replay (+ mirror), backstop positive control, F5 count
This commit is contained in:
Joseph Doherty
2026-11-28 10:26:39 -05:00
parent 06da40a909
commit 099238894c
9 changed files with 250 additions and 63 deletions
@@ -225,8 +225,13 @@ public sealed partial class DriverHostActor
var ownedPaths = owned.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal);
var before = t.Pending.Count;
t.Pending.UnionWith(msg.Args.ConditionIds.Where(ownedPaths.Contains));
// An F5 window already running covers them; otherwise start one now.
if (t.Pending.Count != before && t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t);
// An F5 window already running covers them; otherwise start one now. A diagnostic already raised for
// that window must count them too (#926 review r2).
if (t.Pending.Count != before)
{
if (t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t);
else if (t.DiagnosticRaised) _conditionSignals.Hub?.UpdateUnsignalled(msg.DriverInstanceId, t.Pending.Count);
}
}
_log.Info("DriverHost {Node}: driver {Driver} withdrew {Count} condition(s) ({Routed} routed) — state no longer known (events lost)",
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, withdrawn);
@@ -238,7 +238,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <see cref="AttributeAlarmPublished"/>, so it reaches <see cref="DriverHostActor"/> after every alarm event the
/// driver raised before it.</summary>
/// <remarks>A1 review S2: <paramref name="ConnectionEpoch"/> is the connection (Connected entry) the driver raised
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge.</remarks>
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge. #926: keep this message
/// IN-PROCESS (child → parent only) — it carries <see cref="AlarmInitialStateEventArgs"/> by reference, and a
/// serialized copy that dropped <c>Withdrawn</c> would default it to false and turn a withdrawal into a "known" mark.</remarks>
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args,
long? ConnectionEpoch = null);
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch);
@@ -1165,47 +1165,89 @@ 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").
foreach (var (alarm, _) in _deferred.Alarms)
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) _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
// before it) but wrong for a withdrawal followed by a live transition: replayed transition-then-withdrawal,
// the condition ended unknown although the transition had re-established it — and the host, which saw the
// transition last, no longer counted it in F5. Arrival order is exactly what the live path applies.
var items = new List<(long Seq, int Kind, int Index)>();
var alarmList = _deferred.Alarms.ToList();
var qualityList = _deferred.AlarmQualities.ToList();
var markList = _deferred.Marks.ToList();
for (var i = 0; i < alarmList.Count; i++) items.Add((alarmList[i].Seq, 0, i));
for (var i = 0; i < qualityList.Count; i++) items.Add((qualityList[i].Seq, 1, i));
for (var i = 0; i < markList.Count; i++) items.Add((markList[i].Seq, 2, i));
items.Sort((x, y) => x.Seq.CompareTo(y.Seq));
var alarms = 0;
foreach (var alarm in _deferred.Alarms)
{
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId)))
{
_deferred.NoteAlarmLoss(alarm.Source); // G3: a skipped projection — the source's marks go too
continue;
}
alarms++;
try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
}
var qualities = 0;
foreach (var quality in _deferred.AlarmQualities)
{
if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
qualities++;
try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
}
// A1 F2/G3: the deferred "known" marks replay LAST, after every deferred alarm — and only for a source none of
// whose deferred projections was dropped or skipped. A discarded mark leaves its conditions unknown (Uncertain)
// until the source's next signal.
var marks = 0;
var discarded = 0;
foreach (var (mark, sender) in _deferred.Marks)
var discardedBySender = new Dictionary<(string Source, AddressSpaceRealm Realm), (IActorRef? Sender, List<string> Ids)>();
// Consecutive marks of one (source, realm, known) are applied as one sink call.
string? runSource = null;
AddressSpaceRealm runRealm = default;
var runKnown = false;
var runIds = new List<string>();
void FlushRun()
{
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
if (mark.Known && _deferred.SourceLost(mark.Source))
if (runIds.Count == 0) return;
marks++;
ApplyMark(new MarkConditionsKnown(runSource!, runIds.ToList(), runRealm, runKnown));
runIds.Clear();
}
foreach (var (_, kind, index) in items)
{
if (kind == 2)
{
discarded++;
TellDiscarded(sender, new ConditionMarksDiscarded(mark.Source, mark.ConditionIds, mark.Realm));
var m = markList[index];
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
if (m.Known && _deferred.SourceLost(m.Source))
{
discarded++;
if (!discardedBySender.TryGetValue((m.Source, m.Realm), out var d))
discardedBySender[(m.Source, m.Realm)] = d = (m.Sender, new List<string>());
d.Ids.Add(m.ConditionId);
continue;
}
if (runIds.Count > 0 && (runSource != m.Source || runRealm != m.Realm || runKnown != m.Known)) FlushRun();
runSource = m.Source;
runRealm = m.Realm;
runKnown = m.Known;
runIds.Add(m.ConditionId);
continue;
}
marks++;
ApplyMark(mark);
FlushRun();
if (kind == 0)
{
var alarm = alarmList[index].Msg;
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) continue; // counted in the pre-pass
alarms++;
try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
}
else
{
var quality = qualityList[index].Msg;
if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
qualities++;
try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
}
}
FlushRun();
foreach (var ((source, realm), (sender, ids)) in discardedBySender)
TellDiscarded(sender, new ConditionMarksDiscarded(source, ids, realm));
// N1: a KNOWN mark that did not fit the deferral was dropped (staying unknown is safe) — its sender hears it.
foreach (var (source, sender) in _deferred.OverflowedMarkSources)
@@ -1233,6 +1275,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// the two live writes leave on the node). Bounded by <see cref="Capacity"/> distinct keys across all kinds;
/// beyond it a NEW key is not held (an existing key still updates), counted in <see cref="Dropped"/>.
/// </summary>
/// <summary>One deferred condition-known mark (#926 review r2: per condition, with its arrival sequence).</summary>
private sealed record DeferredMark(
string Source, string ConditionId, AddressSpaceRealm Realm, bool Known, IActorRef? Sender, long Seq);
private sealed class DeferredWrites(int capacity)
{
private struct VariableEntry
@@ -1246,11 +1292,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new();
private readonly Dictionary<(AddressSpaceRealm, string), AlarmStateUpdate> _alarms = new();
private readonly Dictionary<(AddressSpaceRealm, string), AlarmQualityUpdate> _qualities = new();
// A1: condition-known marks in arrival order (bounded by Capacity — a dropped mark only keeps conditions
// unknown, which is always safe), and the sources that lost a deferred alarm projection (G3).
private readonly List<(MarkConditionsKnown Msg, IActorRef? Sender)> _marks = new();
private readonly Dictionary<(AddressSpaceRealm, string), (AlarmStateUpdate Msg, long Seq)> _alarms = new();
private readonly Dictionary<(AddressSpaceRealm, string), (AlarmQualityUpdate Msg, long Seq)> _qualities = new();
// A1 / #926 review r2: the LATEST condition-known mark per (realm, condition id), with its arrival sequence, and
// the sources that lost a deferred alarm projection (G3). Per-condition, so a withdrawal-heavy plan window holds
// at most one entry per condition (bounded by the address space), and replay can interleave marks with alarm
// states in arrival order.
private readonly Dictionary<(AddressSpaceRealm, string), DeferredMark> _marks = new();
private long _seq;
private readonly Dictionary<string, IActorRef?> _overflowedMarkSources = new(StringComparer.Ordinal);
private readonly HashSet<string> _lossySources = new(StringComparer.Ordinal);
private bool _unattributedLoss;
@@ -1259,20 +1308,31 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
public long Dropped { get; private set; }
public int Count => _variables.Count + _alarms.Count + _qualities.Count;
public bool IsEmpty => Count == 0 && _marks.Count == 0;
public IEnumerable<AlarmStateUpdate> Alarms => _alarms.Values;
public IEnumerable<AlarmQualityUpdate> AlarmQualities => _qualities.Values;
public IReadOnlyList<(MarkConditionsKnown Msg, IActorRef? Sender)> Marks => _marks;
public IEnumerable<(AlarmStateUpdate Msg, long Seq)> Alarms => _alarms.Values;
public IEnumerable<(AlarmQualityUpdate Msg, long Seq)> AlarmQualities => _qualities.Values;
public IEnumerable<DeferredMark> Marks => _marks.Values;
/// <summary>
/// Defer a mark. A withdrawal (<c>Known: false</c>) is never dropped — review round 2 N1: staying KNOWN over a
/// lost withdrawal is the unsafe direction, and withdrawals are bounded by connectivity edges. A known mark
/// beyond <see cref="Capacity"/> is dropped (unknown is safe) and its source is remembered so the sender hears
/// of it at replay (N2).
/// Defer a mark, per condition: a later mark of the same condition replaces the earlier (the later one is what
/// the live path leaves). A withdrawal (<c>Known: false</c>) is never dropped — review round 2 N1: staying KNOWN
/// over a lost withdrawal is the unsafe direction. It is bounded anyway: one entry per condition, so at most
/// the number of conditions in the address space (#926 made withdrawals routine, so the old "bounded by
/// connectivity edges" no longer held). A known mark for a NEW condition beyond <see cref="Capacity"/> marks is
/// dropped (unknown is safe) and its source is remembered so the sender hears of it at replay (N2).
/// </summary>
public void Mark(MarkConditionsKnown msg, IActorRef? sender)
{
if (!msg.Known || _marks.Count < Capacity) _marks.Add((msg, sender));
else _overflowedMarkSources[msg.Source] = sender;
foreach (var id in msg.ConditionIds)
{
if (string.IsNullOrEmpty(id)) continue;
var key = (msg.Realm, id);
if (msg.Known && !_marks.ContainsKey(key) && _marks.Count >= Capacity)
{
_overflowedMarkSources[msg.Source] = sender;
continue;
}
_marks[key] = new DeferredMark(msg.Source, id, msg.Realm, msg.Known, sender, ++_seq);
}
}
public IEnumerable<(string Source, IActorRef? Sender)> OverflowedMarkSources =>
@@ -1325,12 +1385,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
public bool Alarm(AlarmStateUpdate msg)
{
var key = (msg.Realm, msg.AlarmNodeId);
if (!Put(_alarms, key, msg)) return false;
if (!Put(_alarms, key, (msg, _seq + 1))) return false;
_seq++;
_qualities.Remove(key);
return true;
}
public bool AlarmQuality(AlarmQualityUpdate msg) => Put(_qualities, (msg.Realm, msg.AlarmNodeId), msg);
public bool AlarmQuality(AlarmQualityUpdate msg)
{
if (!Put(_qualities, (msg.Realm, msg.AlarmNodeId), (msg, _seq + 1))) return false;
_seq++;
return true;
}
public (List<ValueWrite> Values, List<StatusWrite> Statuses) VariableWrites(Func<(AddressSpaceRealm, string), bool> include)
{
@@ -1357,6 +1423,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
_lossySources.Clear();
_unattributedLoss = false;
Dropped = 0;
_seq = 0;
}
private bool Put<T>(Dictionary<(AddressSpaceRealm, string), T> map, (AddressSpaceRealm, string) key, T value)