fix(grpc-data): A1 review round 2 N1 + N2 — withdrawals are never dropped; a discarded mark re-arms F5

N1: the deferral keeps every withdrawal (Known: false) regardless of capacity; a known mark beyond capacity is
dropped (unknown is safe) and its source remembered.
N2: a G3-discarded (or overflowed) deferred mark is reported to its sender as OpcUaPublishActor.ConditionMarksDiscarded
(the scripted host is skipped); DriverHostActor puts those conditions back in the F5 window from now, so a driver
that does not re-signal gets the diagnostic.
This commit is contained in:
Joseph Doherty
2026-11-24 11:34:12 -05:00
parent 4c8539b897
commit 4a6c894268
4 changed files with 127 additions and 6 deletions
@@ -49,6 +49,7 @@ public sealed partial class DriverHostActor
Receive<DriverInstanceActor.AlarmInitialStatePublished>(OnAlarmInitialState);
Receive<ConditionSignalTimedOut>(OnConditionSignalTimedOut);
Receive<ConditionBackstopElapsed>(OnConditionBackstopElapsed);
Receive<PublishActor.ConditionMarksDiscarded>(OnConditionMarksDiscarded);
}
private void ReceiveConditionSignalsWhileStale()
@@ -57,6 +58,7 @@ public sealed partial class DriverHostActor
_log.Debug("DriverHost {Node}: dropping an initial alarm-state signal from {Id} while Stale", _localNode, m.DriverInstanceId));
Receive<ConditionSignalTimedOut>(_ => { });
Receive<ConditionBackstopElapsed>(_ => { });
Receive<PublishActor.ConditionMarksDiscarded>(_ => { });
}
private ConditionSignalTracker Tracker(string driverInstanceId)
@@ -168,6 +170,30 @@ public sealed partial class DriverHostActor
}
}
/// <summary>
/// A1 review round 2 N2: the publish actor discarded a deferred mark of this driver (G3, or the deferral was full),
/// so those conditions are still unknown in the node manager. Put them back in the F5 window (from now), so a
/// driver that does not re-signal raises the "not signalled" diagnostic for them.
/// </summary>
private void OnConditionMarksDiscarded(PublishActor.ConditionMarksDiscarded msg)
{
if (!_conditionSignalTrackers.TryGetValue(msg.Source, out var t) || t.GoodSinceUtc is null) return;
if (!_alarmRefsByDriver.TryGetValue(msg.Source, out var refs)) return;
var owned = refs.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal);
IEnumerable<string> back = msg.ConditionIds is null
? owned
: msg.ConditionIds
.Where(id => _driverRefByAlarmNodeId.TryGetValue(id, out var target) && target.DriverInstanceId == msg.Source)
.Select(id => _driverRefByAlarmNodeId[id].RawPath)
.Where(owned.Contains);
var before = t.Pending.Count;
t.Pending.UnionWith(back);
if (t.Pending.Count == before) return;
_log.Warning("DriverHost {Node}: {Count} deferred condition-known mark(s) of {Driver} were discarded; back in the F5 window until it signals again",
_localNode, t.Pending.Count - before, msg.Source);
ArmSignalTimeout(msg.Source, t);
}
private void OnAlarmInitialState(DriverInstanceActor.AlarmInitialStatePublished msg)
{
if (!IsCurrentChild(msg.DriverInstanceId, Sender))
@@ -100,6 +100,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <param name="Realm">Their realm.</param>
/// <param name="Known">True = mark known; false = withdraw (a scripted input reverted to never-pushed).</param>
public sealed record MarkConditionsKnown(string Source, IReadOnlyList<string> ConditionIds, AddressSpaceRealm Realm, bool Known = true);
/// <summary>
/// A1 review round 2 N2: sent back to the sender of a deferred <see cref="MarkConditionsKnown"/> the G3 rule (or
/// the deferral's capacity) discarded, so its F5 tracker counts those conditions as still unknown again.
/// </summary>
/// <param name="Source">The mark's source (driver instance id).</param>
/// <param name="ConditionIds">The discarded condition ids, or null when an overflowed mark's ids were not kept
/// (= every condition of <paramref name="Source"/>).</param>
/// <param name="Realm">Their realm.</param>
public sealed record ConditionMarksDiscarded(string Source, IReadOnlyList<string>? ConditionIds, AddressSpaceRealm Realm);
/// <summary>Annotate a materialised condition's source-data Quality out of band from any alarm
/// transition (the driver-connectivity path: comms lost → <see cref="OpcUaStatus.BadNoCommunication"/>,
/// restored → <see cref="OpcUaStatus.Good"/>). Routed to <see cref="IOpcUaAddressSpaceSink.WriteAlarmQuality"/>,
@@ -801,10 +811,17 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private void HandleMarkConditionsKnown(MarkConditionsKnown msg)
{
if (PlanPipelineBusy) _deferred.Mark(msg);
if (PlanPipelineBusy) _deferred.Mark(msg, Sender);
ApplyMark(msg);
}
/// <summary>N2: tell a discarded mark's sender (a driver host; the scripted host has no F5 tracker and is skipped).</summary>
private static void TellDiscarded(IActorRef? sender, ConditionMarksDiscarded message)
{
if (sender is null || sender.IsNobody() || message.Source == ScriptedSource) return;
sender.Tell(message);
}
private void ApplyMark(MarkConditionsKnown msg)
{
try
@@ -1176,12 +1193,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
// until the source's next signal.
var marks = 0;
var discarded = 0;
foreach (var mark in _deferred.Marks)
foreach (var (mark, sender) in _deferred.Marks)
{
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
if (mark.Known && _deferred.SourceLost(mark.Source))
{
discarded++;
TellDiscarded(sender, new ConditionMarksDiscarded(mark.Source, mark.ConditionIds, mark.Realm));
continue;
}
@@ -1189,6 +1207,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
ApplyMark(mark);
}
// 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)
{
discarded++;
TellDiscarded(sender, new ConditionMarksDiscarded(source, null, AddressSpaceRealm.Raw));
}
if (discarded > 0)
{
OtOpcUaTelemetry.DataConnConditionMarksDiscarded.Add(discarded);
@@ -1225,7 +1250,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
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> _marks = new();
private readonly List<(MarkConditionsKnown Msg, IActorRef? Sender)> _marks = new();
private readonly Dictionary<string, IActorRef?> _overflowedMarkSources = new(StringComparer.Ordinal);
private readonly HashSet<string> _lossySources = new(StringComparer.Ordinal);
private bool _unattributedLoss;
@@ -1235,13 +1261,23 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
public bool IsEmpty => Count == 0 && _marks.Count == 0;
public IEnumerable<AlarmStateUpdate> Alarms => _alarms.Values;
public IEnumerable<AlarmQualityUpdate> AlarmQualities => _qualities.Values;
public IReadOnlyList<MarkConditionsKnown> Marks => _marks;
public IReadOnlyList<(MarkConditionsKnown Msg, IActorRef? Sender)> Marks => _marks;
public void Mark(MarkConditionsKnown msg)
/// <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).
/// </summary>
public void Mark(MarkConditionsKnown msg, IActorRef? sender)
{
if (_marks.Count < Capacity) _marks.Add(msg);
if (!msg.Known || _marks.Count < Capacity) _marks.Add((msg, sender));
else _overflowedMarkSources[msg.Source] = sender;
}
public IEnumerable<(string Source, IActorRef? Sender)> OverflowedMarkSources =>
_overflowedMarkSources.Select(kv => (kv.Key, kv.Value));
/// <summary>G3: a deferred projection of <paramref name="source"/> was dropped or skipped. An unattributed
/// loss (null source) discards every source's marks.</summary>
public void NoteAlarmLoss(string? source)
@@ -1317,6 +1353,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
_alarms.Clear();
_qualities.Clear();
_marks.Clear();
_overflowedMarkSources.Clear();
_lossySources.Clear();
_unattributedLoss = false;
Dropped = 0;
@@ -212,6 +212,21 @@ public sealed class NativeAlarmInitialStateSignalTests : NativeAlarmSignalTestBa
AssertNoMark(rig.Publish, TimeSpan.FromSeconds(4.5)); // a stale set would arm the 3 s backstop from this Good edge
}
/// <summary>Review round 2 N2: a discarded mark reported back by the publish actor puts its conditions back in the F5
/// window, so a driver that does not re-signal raises the diagnostic for them.</summary>
[Fact]
public void A_discarded_mark_rearms_F5_for_its_conditions()
{
var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"], o => o.WithSignalTimeout(DriverTypeNames.Galaxy, TimeSpan.FromMilliseconds(400)));
rig.Driver.Signal([A, B]).ShouldBeTrue();
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct);
rig.Host.Tell(new OpcUaPublishActor.ConditionMarksDiscarded(DriverId, [A], AddressSpaceRealm.Raw), TestActor);
AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct);
rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(1);
}
/// <summary>Open question answered — re-arm F5 for refs a deploy adds while the driver is connected. Today every such
/// deploy changes the driver's config (its authored RawTags are folded into it), so the driver is respawned: the
/// stopped incarnation's conditions are withdrawn, and the new incarnation's Good edge puts EVERY ref — the added one
@@ -169,6 +169,49 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
AwaitAssert(() => sink.Completions.ShouldBe([false, true]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Review round 2 N1: a deferred withdrawal is never dropped by the deferral's capacity (a known mark may be —
/// unknown is the safe side).</summary>
[Fact]
public void A_withdrawal_beyond_the_deferral_capacity_is_never_dropped()
{
var sink = new OrderSink("al-1");
using var gate = new ManualResetEventSlim(false);
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
new OpcUaPublishActor.TestHooks { BeforePlan = () => gate.Wait() }, deferredWriteCapacity: 1));
actor.Tell(Rebuild());
for (var i = 0; i < 3; i++) actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns, Known: false));
AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(3), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(6), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Review round 2 N2: a G3 discard of a driver's deferred mark is reported back to the mark's sender, so its
/// F5 tracker counts those conditions as unknown again.</summary>
[Fact]
public void A_discarded_driver_mark_is_reported_to_its_sender()
{
var sink = new OrderSink();
using var gate = new ManualResetEventSlim(false);
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
new OpcUaPublishActor.TestHooks { BeforePlan = () => gate.Wait() }, deferredWriteCapacity: 1));
actor.Tell(Rebuild());
actor.Tell(new OpcUaPublishActor.AttributeValueBatchUpdate([new ValueWrite("Plant/x", 1, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw)]));
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1"));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate.Set();
var discarded = FishForMessage<OpcUaPublishActor.ConditionMarksDiscarded>(_ => true, PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
discarded.Source.ShouldBe("drv-1");
discarded.ConditionIds.ShouldBe(["al-1"]);
}
private IActorRef Spawn(OrderSink sink, ManualResetEventSlim gate) =>
Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),