Merge branch 'review/wp3' into review/integration

This commit is contained in:
Joseph Doherty
2026-12-03 10:41:19 -05:00
45 changed files with 2862 additions and 277 deletions
@@ -14,7 +14,26 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types;
/// </summary>
public static class AttributeValueCodec
{
private static readonly JsonSerializerOptions JsonOpts = new() { WriteIndented = false };
// AllowNamedFloatingPointLiterals: a List<double>/List<float> holding NaN or ±Infinity
// (a bad-scaled analog, a divide-by-zero) encodes as the JSON strings "NaN" /
// "Infinity" / "-Infinity" instead of throwing ArgumentException from the serializer
// (CMN-3). Decode reads them back through the invariant-culture double/float parse,
// which accepts the same literals.
private static readonly JsonSerializerOptions JsonOpts = new()
{
WriteIndented = false,
NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals,
};
/// <summary>
/// The scalar DateTime wire format: ISO-8601 round-trip (<c>"O"</c>), always UTC, with
/// full sub-second precision. Replaced the invariant general format
/// (<c>"06/15/2026 13:45:30"</c> — no zone, whole seconds) that the
/// <see cref="IFormattable"/> branch used to produce (CMN-4). Every reader parses with
/// <see cref="DateTimeStyles.RoundtripKind"/> + invariant culture, which still accepts
/// the old form, so values persisted or sent by an older node keep decoding.
/// </summary>
private const string DateTimeWireFormat = "O";
/// <summary>Encodes a value to its canonical string form.</summary>
/// <param name="value">The value to encode; scalars use invariant-culture formatting, enumerables encode as a JSON array.</param>
@@ -25,6 +44,12 @@ public static class AttributeValueCodec
{
case null: return null;
case string s: return s; // already canonical
// DateTime/DateTimeOffset before the generic IFormattable branch: ISO-8601
// round-trip so the scalar keeps its zone and sub-second precision (CMN-4).
// All timestamps are UTC system-wide, so an Unspecified kind is taken as UTC
// and a Local one is converted.
case DateTime dt: return ToUtc(dt).ToString(DateTimeWireFormat, CultureInfo.InvariantCulture);
case DateTimeOffset dto: return dto.ToString(DateTimeWireFormat, CultureInfo.InvariantCulture);
case IFormattable f: return f.ToString(null, CultureInfo.InvariantCulture);
case IEnumerable e:
// Native-typed JSON: serialize the runtime collection so System.Text.Json emits
@@ -35,6 +60,13 @@ public static class AttributeValueCodec
}
}
private static DateTime ToUtc(DateTime dt) => dt.Kind switch
{
DateTimeKind.Utc => dt,
DateTimeKind.Local => dt.ToUniversalTime(),
_ => DateTime.SpecifyKind(dt, DateTimeKind.Utc),
};
/// <summary>
/// Decodes a canonical string. For <see cref="DataType.List"/> returns a typed
/// <c>List&lt;T&gt;</c>; for scalars returns the string unchanged. Throws
@@ -96,7 +96,20 @@ public class DynamicJsonElement : DynamicObject
return true;
}
result = ConvertTo(binder.Type);
// A JSON null converts to null for any target that can hold null (reference
// types and Nullable<T>), e.g. (string)resp or (int?)resp on a JSON-null body.
// A non-nullable value type (e.g. int) genuinely cannot represent it: report
// failure so the binder surfaces a binding error (CMN-10).
var underlying = Nullable.GetUnderlyingType(binder.Type);
if (_element.ValueKind == JsonValueKind.Null)
{
result = null;
return !binder.Type.IsValueType || underlying != null;
}
// Nullable<T> targets convert through their underlying type: (int?)resp on a
// JSON number yields the boxed int, which the binder lifts to int?.
result = ConvertTo(underlying ?? binder.Type);
// A non-object target with a null result means ConvertTo could not handle the
// element/type pair — report failure so the binder surfaces a binding error.
return result != null;
@@ -492,6 +492,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
// No session yet — a probe would fail for every tag. ReSubscribeAll's chunk
// completions re-arm the timer once the link is up.
break;
case RetryAlarmResubscribe:
// No session — ReSubscribeAllAlarms re-issues every feed once the link is up.
break;
case ServiceLevelPollTick or ServiceLevelSampled or ServiceLevelProbed:
// ScadaBridge#138: belongs to a session that is over; BecomeConnected restarts it.
break;
@@ -621,6 +624,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
case RetryTagResolution:
HandleRetryTagResolution();
break;
case RetryAlarmResubscribe retryAlarm:
HandleRetryAlarmResubscribe(retryAlarm);
break;
case BrowseNodeCommand browse:
HandleBrowse(browse);
break;
@@ -985,6 +991,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
// Ignore — the adapter has no live session; ReSubscribeAll's chunk
// completions re-arm the retry timer after reconnect.
break;
case RetryAlarmResubscribe:
// Ignore — ReSubscribeAllAlarms re-issues every feed after reconnect.
break;
case ServiceLevelProbed { AfterDisconnect: true } lostLinkProbe:
// ScadaBridge#141: the other endpoint's verdict for a link lost after a Degraded level.
HandleDisconnectProbed(lostLinkProbe);
@@ -1260,6 +1269,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
ReSubscribeAllAlarms();
BecomeConnected();
PushConnectionRestored();
}
else
{
@@ -1970,7 +1980,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
foreach (var seed in msg.SeedValues)
{
if (_subscriptionIds.ContainsKey(seed.TagPath))
Self.Tell(new TagValueReceived(seed.TagPath, seed.Value, _adapterGeneration));
Self.Tell(new TagValueReceived(seed.TagPath, seed.Value, _adapterGeneration, SeedKind.InitialSubscribe));
}
}
@@ -2268,7 +2278,20 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
_log.Debug("[{0}] Browsing children of {1}", _connectionName, command.ParentNodeId ?? "(root)");
browsable.BrowseChildrenAsync(command.ParentNodeId, command.ContinuationToken).ContinueWith(t =>
// DCL-6: an adapter that throws BEFORE returning a task (not yet connected, a null client)
// must still produce a typed reply — the mapping below only sees a faulted task, so a
// synchronous throw used to escape on the actor thread and leave the caller to time out.
Task<BrowseChildrenResult> browseTask;
try
{
browseTask = browsable.BrowseChildrenAsync(command.ParentNodeId, command.ContinuationToken);
}
catch (Exception ex)
{
browseTask = Task.FromException<BrowseChildrenResult>(ex);
}
browseTask.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
{
@@ -2349,7 +2372,18 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
_log.Debug("[{0}] Searching address space for '{1}' (maxDepth={2}, maxResults={3})",
_connectionName, command.Query, command.MaxDepth, command.MaxResults);
searchable.SearchAddressSpaceAsync(command.Query, command.MaxDepth, command.MaxResults).ContinueWith(t =>
// DCL-6: see HandleBrowse — a synchronous throw must still reply.
Task<AddressSpaceSearchResult> searchTask;
try
{
searchTask = searchable.SearchAddressSpaceAsync(command.Query, command.MaxDepth, command.MaxResults);
}
catch (Exception ex)
{
searchTask = Task.FromException<AddressSpaceSearchResult>(ex);
}
searchTask.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
{
@@ -2633,7 +2667,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
{
var seeds = await SeedTagsAsync(adapter, resolved);
foreach (var seed in seeds)
self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation));
self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation, SeedKind.Reseed));
}
catch (Exception ex)
{
@@ -2780,10 +2814,17 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
}
else if (row.ConnectionLevelFailure)
{
// Connection-level fault: not a tag-resolution problem. The reconnect
// cycle re-issues everything from _subscriptionsByInstance.
// Connection-level fault on a re-subscribe / probe row. If the adapter also
// raises Disconnected, the reconnect cycle re-issues everything from
// _subscriptionsByInstance — but nothing here starts that cycle, and
// ReSubscribeAll already cleared _subscriptionIds/_unresolvedTags, so a
// chunk that failed while the session stayed healthy used to leave its tags
// in NO retry set: Bad until some unrelated reconnect (DCL-8). Put them in
// the resolution retry set; a reconnect clears it and re-issues them anyway.
_log.Warning("[{0}] Batch subscribe for {1} failed at connection level: {2}",
_connectionName, row.TagPath, row.Error);
if (_instancesByTag.ContainsKey(row.TagPath) && !_subscriptionIds.ContainsKey(row.TagPath))
_unresolvedTags.Add(row.TagPath);
}
else
{
@@ -2819,6 +2860,27 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
ScheduleTagResolutionRetry();
}
// ── Connection-restored signal ──
/// <summary>
/// SRT-6 / WP3 task 3.8: tells every subscriber <c>ConnectionQualityChanged(Good)</c> when the
/// connection re-enters Connected after a reconnect. It is a RESTORE SIGNAL only — the Instance
/// Actor uses it to reset its Lever-1 tag-subscribe backoff so a subscribe that failed during
/// the outage is retried at the floor instead of up to <c>TagSubscribeRetryMaxIntervalMs</c>
/// later. It deliberately says nothing about any tag's value: per-tag quality is restored by
/// the re-subscribe and the re-seed, and the Instance Actor must not stamp bound attributes
/// Good with their last-known values before the device re-reports.
/// </summary>
private void PushConnectionRestored()
{
var now = DateTimeOffset.UtcNow;
foreach (var instanceName in _subscriptionsByInstance.Keys)
{
if (_subscribers.TryGetValue(instanceName, out var subscriber))
subscriber.Tell(new ConnectionQualityChanged(_connectionName, QualityCode.Good, now));
}
}
// ── Bad Quality Push ──
private void PushBadQualityForAllTags()
@@ -2939,6 +3001,17 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
var batchSize = Math.Max(1, _options.SubscribeBatchSize);
var chunkDelay = _options.SubscribeBatchDelay;
// Session-bound background work (the re-subscribe loop below AND the re-seed further
// down) shares ONE token, created BEFORE either starts. CancelSessionWork — entering
// Reconnecting, an adapter swap, actor stop — cancels it. DCL-4: the loop used to have
// no token, so a loop left over from a dead session (a chunk wedged across a reconnect)
// carried on issuing its remaining chunks against the SAME adapter object's NEW client:
// duplicate OPC UA monitored items / MxGateway subscribes whose stale-generation results
// were then dropped without release.
CancelSessionWork();
_sessionWorkCts = new CancellationTokenSource();
var sessionToken = _sessionWorkCts.Token;
// Bounded, sequential chunks in ONE background task — replacing the previous
// "one fire-and-forget task per tag" storm (37,500 concurrent subscribes at the
// sizing target). Sequential because subscription creation on one session is
@@ -2949,8 +3022,22 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
{
for (var offset = 0; offset < allTags.Count; offset += batchSize)
{
if (offset > 0 && chunkDelay > TimeSpan.Zero)
await Task.Delay(chunkDelay);
try
{
if (offset > 0 && chunkDelay > TimeSpan.Zero)
await Task.Delay(chunkDelay, sessionToken);
}
catch (OperationCanceledException)
{
// Fall through to the cancellation check below.
}
if (sessionToken.IsCancellationRequested)
{
_log.Debug("[{0}] Reconnect re-subscribe abandoned at tag {1}/{2} — its session has ended",
_connectionName, offset, allTags.Count);
return;
}
var chunk = allTags.GetRange(offset, Math.Min(batchSize, allTags.Count - offset));
try
@@ -2984,16 +3071,14 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
// repopulated for the new adapter generation. Seeds delivered after registration is
// already established, so the ordering hazard does not apply here.
var reseedAdapter = _adapter;
CancelSessionWork();
_sessionWorkCts = new CancellationTokenSource();
var reseedToken = _sessionWorkCts.Token;
var reseedToken = sessionToken;
Task.Run(async () =>
{
try
{
var seeds = await SeedTagsAsync(reseedAdapter, allTags, reseedToken);
foreach (var seed in seeds)
self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation));
self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation, SeedKind.Reseed));
}
catch (Exception ex)
{
@@ -3041,9 +3126,24 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
private void UnindexTag(string tag, string instance)
{
if (_instancesByTag.TryGetValue(tag, out var insts) && insts.Remove(instance) && insts.Count == 0)
{
_instancesByTag.Remove(tag);
_lastLiveValue.Remove(tag);
}
}
/// <summary>
/// DCL-1: the latest LIVE (subscription-delivered, non-seed) value per tag in the generation
/// recorded in <see cref="_liveValuesGeneration"/>. A tag present here has already delivered a
/// live value in the current subscribe generation, so a later seed for it is stale. Cleared
/// lazily when the adapter generation advances (every reconnect / adapter swap); an entry is
/// dropped when the tag loses its last subscriber.
/// </summary>
private readonly Dictionary<string, TagValue> _lastLiveValue = new();
/// <summary>The adapter generation <see cref="_lastLiveValue"/> belongs to.</summary>
private int _liveValuesGeneration = -1;
private void HandleTagValueReceived(TagValueReceived msg)
{
// Drop values delivered by a disposed adapter. After a
@@ -3064,6 +3164,38 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
if (!_instancesByTag.TryGetValue(msg.TagPath, out var interestedInstances))
return;
// DCL-1: a seed must never overwrite a newer live value. The subscription is live
// before the seed read starts, and a seed is held until its whole seed operation
// completes, so a live change inside that window would otherwise be regressed to the
// older seed value — with Good quality, indefinitely, for a tag that changes rarely.
// The rule is generation-based (decided 2026-12-03), NOT a timestamp comparison,
// which would depend on device/server clocks and the configured timestamp mode.
if (_liveValuesGeneration != _adapterGeneration)
{
_lastLiveValue.Clear();
_liveValuesGeneration = _adapterGeneration;
}
var value = msg.Value;
if (msg.Seed == SeedKind.None)
{
_lastLiveValue[msg.TagPath] = value;
}
else if (_lastLiveValue.TryGetValue(msg.TagPath, out var latestLive))
{
if (msg.Seed == SeedKind.Reseed)
{
// Every interested instance was registered while the subscription was live,
// so each already holds the live value: drop the seed outright.
_log.Debug("[{0}] Dropping seed for {1}: a live value already arrived in generation {2}",
_connectionName, msg.TagPath, _adapterGeneration);
return;
}
// Initial subscribe: the joining instance may have missed live values delivered
// before it registered, so re-deliver the LATEST live value instead of the seed.
value = latestLive;
}
// Fan out to exactly the instances subscribed to this tag via the reverse index —
// O(subscribers of this tag) instead of scanning every instance's tag set per update.
foreach (var instanceName in interestedInstances)
@@ -3071,7 +3203,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
if (_subscribers.TryGetValue(instanceName, out var subscriber))
{
subscriber.Tell(new TagValueUpdate(
_connectionName, msg.TagPath, msg.Value.Value, msg.Value.Quality, msg.Value.Timestamp));
_connectionName, msg.TagPath, value.Value, value.Quality, value.Timestamp));
}
}
@@ -3082,7 +3214,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
// 30s. Now: unchanged quality is a no-op; a genuine transition updates the buckets
// and arms the coalescing flush timer.
var hadPrevious = _lastTagQuality.TryGetValue(msg.TagPath, out var prevQuality);
if (hadPrevious && prevQuality == msg.Value.Quality)
if (hadPrevious && prevQuality == value.Quality)
return;
if (hadPrevious)
@@ -3096,13 +3228,13 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
}
}
// Increment new quality bucket
switch (msg.Value.Quality)
switch (value.Quality)
{
case QualityCode.Good: _tagsGoodQuality++; break;
case QualityCode.Bad: _tagsBadQuality++; break;
case QualityCode.Uncertain: _tagsUncertainQuality++; break;
}
_lastTagQuality[msg.TagPath] = msg.Value.Quality;
_lastTagQuality[msg.TagPath] = value.Quality;
MarkQualityDirty();
}
@@ -3356,8 +3488,19 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
{
_log.Warning("[{0}] Alarm subscribe failed for source {1}: {2}",
_connectionName, msg.SourceReference, msg.Error);
// DCL-2: a reconnect re-subscribe (ReplyTo == null) has no requester to retry it —
// the NativeAlarmActor already counts the feed as established and its
// NativeAlarmSourceUnavailable handler deliberately does not re-subscribe — so the
// DCL retries it itself on a backed-off timer while the source still has
// subscribers. An interactive subscribe's failure is retried by its requester.
if (msg.ReplyTo is null)
ScheduleAlarmResubscribeRetry(msg.SourceReference);
}
if (msg.Success)
CancelAlarmResubscribeRetry(msg.SourceReference);
// ReplyTo is null for reconnect re-subscribes (no original requester to answer).
msg.ReplyTo?.Tell(new SubscribeAlarmsResponse(
msg.CorrelationId ?? string.Empty, msg.InstanceUniqueName ?? string.Empty,
@@ -3402,9 +3545,10 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
continue;
// A subscriber bound to source S receives a transition whose source
// object (or full reference) falls under S.
var match = transition.SourceObjectReference.StartsWith(sourceRef, StringComparison.Ordinal)
|| transition.SourceReference.StartsWith(sourceRef, StringComparison.Ordinal);
// object (or full reference) falls under S — S itself or a descendant
// separated by a path separator, never a mere string prefix (DCL-5).
var match = IsUnderAlarmSource(transition.SourceObjectReference, sourceRef)
|| IsUnderAlarmSource(transition.SourceReference, sourceRef);
if (!match)
continue;
@@ -3484,6 +3628,29 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
/// full StartsWith test and the condition-type gate, so routing is identical to the
/// previous linear scan.
/// </summary>
/// <summary>
/// True when <paramref name="reference"/> is the alarm source <paramref name="source"/> itself or
/// lies beneath it: the prefix must end at a path separator (<c>.</c> or <c>/</c>). A raw string
/// prefix let <c>Tank1</c> (or <c>ns=2;s=Tank1</c>) also receive — and mirror as its own —
/// every alarm of <c>Tank10</c> (DCL-5). An empty source (the OPC UA Server-object aggregate
/// feed) covers everything, as before.
/// </summary>
internal static bool IsUnderAlarmSource(string reference, string source)
{
if (source.Length == 0)
return true;
if (!reference.StartsWith(source, StringComparison.Ordinal))
return false;
if (reference.Length == source.Length)
return true;
// The source already ends in a separator (an explicit area prefix such as "Area1.").
var last = source[^1];
if (last is '.' or '/')
return true;
var next = reference[source.Length];
return next is '.' or '/';
}
private IEnumerable<string> CandidateAlarmSources(NativeAlarmTransition transition)
{
var objectSegment = FirstSegment(transition.SourceObjectReference);
@@ -3526,6 +3693,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
UnindexAlarmSource(sourceReference);
_alarmSourceFilter.Remove(sourceReference);
_alarmSourceFilterPredicate.Remove(sourceReference);
CancelAlarmResubscribeRetry(sourceReference);
// Clear the in-flight marker so that if an adapter
// subscribe is still in flight for this source, the late AlarmSubscribeCompleted
// is recognized as orphaned (its guard checks _alarmSourceSubscribers, now empty)
@@ -3547,24 +3715,89 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
_alarmSubscriptionIds.Clear();
_alarmReplay.Clear();
_alarmSubscribesInFlight.Clear();
var self = Self;
var generation = _adapterGeneration;
// A fresh session re-issues every feed: retries armed against the previous one are moot
// and their backoff starts over.
foreach (var sourceRef in _alarmResubscribeInterval.Keys.ToList())
CancelAlarmResubscribeRetry(sourceRef);
foreach (var sourceRef in _alarmSourceSubscribers.Keys.ToList())
IssueAlarmResubscribe(alarmable, sourceRef);
}
/// <summary>
/// Issues one requester-less (<c>ReplyTo == null</c>) alarm-feed subscribe for
/// <paramref name="sourceRef"/> against <paramref name="alarmable"/> — the reconnect
/// re-subscribe and its DCL-2 retry.
/// </summary>
private void IssueAlarmResubscribe(IAlarmSubscribableConnection alarmable, string sourceRef)
{
var self = Self;
var generation = _adapterGeneration;
var sr = sourceRef;
var filter = _alarmSourceFilter.GetValueOrDefault(sourceRef);
_alarmSubscribesInFlight.Add(sr);
alarmable.SubscribeAlarmsAsync(sr, filter,
t => self.Tell(new AlarmTransitionReceived(t, generation)))
.ContinueWith(task => task.IsCompletedSuccessfully
? new AlarmSubscribeCompleted(
sr, true, task.Result, null, null, null, null, generation, alarmable) as object
: new AlarmSubscribeCompleted(sr, false, null,
task.Exception?.GetBaseException().Message ?? "Unknown error",
null, null, null, generation, alarmable))
.PipeTo(self);
}
// ── DCL-2: alarm re-subscribe retry ──
/// <summary>
/// Next retry delay per alarm source whose requester-less re-subscribe failed. Same floor,
/// doubling and ceiling as the tag-resolution probe
/// (<see cref="DataConnectionOptions.TagResolutionRetryInterval"/> →
/// <see cref="DataConnectionOptions.TagResolutionRetryMaxInterval"/>).
/// </summary>
private readonly Dictionary<string, TimeSpan> _alarmResubscribeInterval = new();
private static string AlarmResubscribeTimerKey(string sourceRef) => "alarm-resubscribe:" + sourceRef;
private void ScheduleAlarmResubscribeRetry(string sourceRef)
{
if (!_alarmSourceSubscribers.ContainsKey(sourceRef))
return;
var delay = _alarmResubscribeInterval.TryGetValue(sourceRef, out var current)
? current
: _options.TagResolutionRetryInterval;
_alarmResubscribeInterval[sourceRef] = NextTagResolutionInterval(
delay, _options.TagResolutionRetryInterval, _options.TagResolutionRetryMaxInterval);
Timers.StartSingleTimer(AlarmResubscribeTimerKey(sourceRef),
new RetryAlarmResubscribe(sourceRef, _adapterGeneration), delay);
_log.Info("[{0}] Alarm feed for source {1} will be re-subscribed in {2}",
_connectionName, sourceRef, delay);
}
private void CancelAlarmResubscribeRetry(string sourceRef)
{
_alarmResubscribeInterval.Remove(sourceRef);
Timers.Cancel(AlarmResubscribeTimerKey(sourceRef));
}
private void HandleRetryAlarmResubscribe(RetryAlarmResubscribe msg)
{
// A retry armed against an earlier session is moot: the reconnect re-issued every feed.
if (msg.AdapterGeneration != _adapterGeneration)
return;
if (!_alarmSourceSubscribers.ContainsKey(msg.SourceReference))
{
var sr = sourceRef;
var filter = _alarmSourceFilter.GetValueOrDefault(sourceRef);
_alarmSubscribesInFlight.Add(sr);
alarmable.SubscribeAlarmsAsync(sr, filter,
t => self.Tell(new AlarmTransitionReceived(t, generation)))
.ContinueWith(task => task.IsCompletedSuccessfully
? new AlarmSubscribeCompleted(
sr, true, task.Result, null, null, null, null, generation, alarmable) as object
: new AlarmSubscribeCompleted(sr, false, null,
task.Exception?.GetBaseException().Message ?? "Unknown error",
null, null, null, generation, alarmable))
.PipeTo(self);
CancelAlarmResubscribeRetry(msg.SourceReference);
return;
}
if (_alarmSubscriptionIds.ContainsKey(msg.SourceReference)
|| _alarmSubscribesInFlight.Contains(msg.SourceReference)
|| _adapter is not IAlarmSubscribableConnection alarmable)
return;
_log.Info("[{0}] Retrying alarm feed subscribe for source {1}", _connectionName, msg.SourceReference);
IssueAlarmResubscribe(alarmable, msg.SourceReference);
}
/// <summary>Notifies alarm subscribers that the source feed is unavailable (connection lost).</summary>
@@ -3593,9 +3826,40 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
/// swapped-out adapter can be dropped (<see cref="IsStaleDisconnect"/>).
/// </summary>
internal record AdapterDisconnected(int AdapterGeneration);
internal record TagValueReceived(string TagPath, TagValue Value, int AdapterGeneration);
/// <summary>
/// A tag value marshalled onto the actor thread. <paramref name="Seed"/> marks a value that
/// came from a seed READ rather than the live subscription (DCL-1): a seed is held until its
/// whole seed operation completes (up to <see cref="DataConnectionOptions.SeedOverallTimeout"/>),
/// so it can be older than a live value the subscription has already delivered.
/// </summary>
internal record TagValueReceived(string TagPath, TagValue Value, int AdapterGeneration, SeedKind Seed = SeedKind.None);
/// <summary>Origin of a <see cref="TagValueReceived"/> (DCL-1).</summary>
internal enum SeedKind
{
/// <summary>A live subscription notification.</summary>
None,
/// <summary>
/// A seed read for tags every interested instance was already registered for while the
/// subscription was live: the reconnect re-seed and the tag-resolution re-seed. Dropped
/// when the tag already delivered a live value in the current generation.
/// </summary>
Reseed,
/// <summary>
/// The seed read of an initial <see cref="SubscribeTagsRequest"/>. The requesting instance
/// may have joined a tag that was ALREADY live for another instance, so it never saw the
/// earlier live values; when the tag has delivered a live value in the current generation
/// the stale seed is replaced by that latest live value rather than dropped outright.
/// </summary>
InitialSubscribe,
}
internal record RetryTagResolution;
/// <summary>DCL-2: backed-off retry of a failed requester-less alarm-feed re-subscribe.</summary>
internal record RetryAlarmResubscribe(string SourceReference, int AdapterGeneration);
/// <summary>Coalescing-timer tick for the tag-quality counter push.</summary>
internal record QualityFlushTick;
@@ -370,7 +370,10 @@ public class MxGatewayDataConnection
// ONE gateway round trip per batch (SubscribeBulk = AddItem + Advise per tag in a
// single worker pass) instead of the historical 2 RPCs per tag.
var session = Volatile.Read(ref _session);
var outcomes = await _client!.SubscribeBulkAsync(tagPaths, cancellationToken);
// Dereference the session's client ONCE (DCL-4); results from a session that ended
// mid-call are not registered (the `current` check below).
var client = _client!;
var outcomes = await client.SubscribeBulkAsync(tagPaths, cancellationToken);
var current = session == Volatile.Read(ref _session);
var results = new List<TagSubscribeResult>(outcomes.Count);
foreach (var outcome in outcomes)
@@ -215,10 +215,13 @@ public class OpcUaDataConnection
IReadOnlyList<string> tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default)
{
EnsureConnected();
// Dereference the session's client ONCE (DCL-4): a reconnect swaps _client, and a call
// must run entirely against the client it started on.
var client = _client!;
// ONE shared callback for the whole batch — the client hands back the node id
// (== tag path for OPC UA), so no per-tag closure is needed.
var outcomes = await _client!.CreateSubscriptionsAsync(
var outcomes = await client.CreateSubscriptionsAsync(
tagPaths,
(nodeId, value, timestamp, statusCode) =>
{
@@ -445,23 +448,33 @@ public class OpcUaDataConnection
}
/// <inheritdoc />
public Task<BrowseChildrenResult> BrowseChildrenAsync(
public async Task<BrowseChildrenResult> BrowseChildrenAsync(
string? parentNodeId,
string? continuationToken = null,
CancellationToken cancellationToken = default)
=> _client!.BrowseChildrenAsync(parentNodeId, continuationToken, cancellationToken);
{
// async so a not-connected adapter FAULTS the task instead of throwing synchronously
// (DCL-6): a freshly swapped failover adapter has no client until the reconnect timer
// fires, and the old `_client!` dereference threw a NullReferenceException on the actor
// thread, so the caller got no reply at all.
var client = _client
?? throw new ConnectionNotConnectedException("OPC UA client is not connected.");
return await client.BrowseChildrenAsync(parentNodeId, continuationToken, cancellationToken);
}
/// <inheritdoc />
public Task<AddressSpaceSearchResult> SearchAddressSpaceAsync(
public async Task<AddressSpaceSearchResult> SearchAddressSpaceAsync(
string query, int maxDepth, int maxResults, CancellationToken cancellationToken = default)
{
// Guard connection state with the typed ConnectionNotConnectedException so
// the site-side handler can map it uniformly (mirrors BrowseChildrenAsync,
// whose underlying client throws the same type when the session is down).
if (_client == null || !_client.IsConnected)
// async so the guard faults the task rather than throwing synchronously (DCL-6).
var client = _client;
if (client == null || !client.IsConnected)
throw new ConnectionNotConnectedException("OPC UA client is not connected.");
return _client.SearchAddressSpaceAsync(query, maxDepth, maxResults, cancellationToken);
return await client.SearchAddressSpaceAsync(query, maxDepth, maxResults, cancellationToken);
}
private void StopHeartbeatMonitor()
@@ -56,6 +56,26 @@ internal static class OpcUaValueBoundary
internal static DateTime ToClrTimestamp(DateTimeUtc value) =>
value == DateTimeUtc.MinValue ? DateTime.MinValue : value.ToDateTime();
/// <summary>
/// The timestamp to stamp on a value read or notified from the server: the SOURCE timestamp
/// when present, else the SERVER timestamp, else now (DCL-7). A connection configured for
/// <c>TimestampsToReturn = Server</c> gets no source timestamp at all, and a server may omit it
/// on notifications; taking <c>SourceTimestamp</c> unconditionally stamped such values
/// <c>0001-01-01T00:00:00Z</c>, which was stored, streamed and shown until the tag next changed.
/// One helper for both the read and the notification path.
/// </summary>
/// <param name="source">The DataValue's source timestamp.</param>
/// <param name="server">The DataValue's server timestamp.</param>
/// <returns>The effective UTC timestamp, never <see cref="DateTime.MinValue"/>.</returns>
internal static DateTime EffectiveTimestamp(DateTimeUtc source, DateTimeUtc server)
{
var fromSource = ToClrTimestamp(source);
if (fromSource != DateTime.MinValue)
return fromSource;
var fromServer = ToClrTimestamp(server);
return fromServer != DateTime.MinValue ? fromServer : DateTime.UtcNow;
}
/// <summary>
/// The SDK value to write for a CLR payload, with SDK 1.5's <c>new Variant(object)</c>
/// semantics: a <c>byte[]</c> is a ByteString scalar, other supported scalars and
@@ -47,6 +47,20 @@ public sealed class RealMxGatewayClient : IMxGatewayClient
// completed. A faulted advise is evicted so the next write retries.
private readonly ConcurrentDictionary<int, Lazy<Task>> _supervisoryAdvised = new();
/// <summary>
/// Cancelled on <see cref="DisposeAsync"/>. The SHARED supervisory-advise task runs under
/// this (plus <see cref="SharedSupervisoryAdviseTimeout"/>), never under the token of
/// whichever caller happened to create it (DCL-9).
/// </summary>
private readonly CancellationTokenSource _lifetime = new();
/// <summary>
/// Upper bound on one shared supervisory advise. The gateway session has no command
/// deadline of its own yet, so without a bound a hung advise would wedge every later
/// caller for that handle; a timed-out advise is evicted and the next caller retries.
/// </summary>
internal static readonly TimeSpan SharedSupervisoryAdviseTimeout = TimeSpan.FromSeconds(60);
// With no configured MXAccess write-user this connection behaves as a
// supervisory client: every advise defaults to AdviseSupervisory so writes are
// accepted. A configured write-user keeps the prior plain-advise behaviour.
@@ -517,6 +531,7 @@ public sealed class RealMxGatewayClient : IMxGatewayClient
/// <returns>A task that represents the asynchronous operation.</returns>
public async ValueTask DisposeAsync()
{
_lifetime.Cancel();
if (_session is not null) await _session.DisposeAsync().ConfigureAwait(false);
if (_client is not null) await _client.DisposeAsync().ConfigureAwait(false);
if (_galaxy is not null) await _galaxy.DisposeAsync().ConfigureAwait(false);
@@ -633,27 +648,46 @@ public sealed class RealMxGatewayClient : IMxGatewayClient
/// builds every other command). The result is remembered per handle; a failure is
/// not cached so the next attempt retries rather than wedging the item permanently.
/// </summary>
private async Task EnsureSupervisoryAdvisedAsync(int handle, CancellationToken ct)
internal async Task EnsureSupervisoryAdvisedAsync(int handle, CancellationToken ct)
{
// GetOrAdd + Lazy runs the advise at most once per handle; concurrent
// callers await the same Task and so never reach WriteBulk before it
// completes (default Lazy is thread-safe, factory runs once).
//
// DCL-9: the shared task must NOT capture the creating caller's token — a write's 30 s
// deadline firing would cancel the advise a concurrent, deadline-free subscribe is also
// awaiting, failing that subscribe as a tag-resolution error. The shared advise runs under
// the client lifetime (bounded by SharedSupervisoryAdviseTimeout); each caller applies its
// OWN token to its wait only.
var advise = _supervisoryAdvised.GetOrAdd(
handle,
h => new Lazy<Task>(() => AdviseSupervisoryCoreAsync(h, ct)));
h => new Lazy<Task>(() => RunSharedSupervisoryAdviseAsync(h)));
try
{
await advise.Value.ConfigureAwait(false);
await advise.Value.WaitAsync(ct).ConfigureAwait(false);
}
catch
{
// Evict the faulted entry (only if it's still the one we awaited) so the
// next write retries rather than caching a transient advise failure.
_supervisoryAdvised.TryRemove(new KeyValuePair<int, Lazy<Task>>(handle, advise));
// Evict a faulted/cancelled SHARED entry (only if it's still the one we awaited) so
// the next call retries rather than caching a transient advise failure. A caller that
// merely stopped waiting on its own token leaves the shared advise running for the
// others.
if (advise.Value.IsFaulted || advise.Value.IsCanceled)
_supervisoryAdvised.TryRemove(new KeyValuePair<int, Lazy<Task>>(handle, advise));
throw;
}
}
private async Task RunSharedSupervisoryAdviseAsync(int handle)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
cts.CancelAfter(SharedSupervisoryAdviseTimeout);
await (AdviseCoreOverride ?? AdviseSupervisoryCoreAsync)(handle, cts.Token).ConfigureAwait(false);
}
/// <summary>Test seam: replaces the gateway round trip of one supervisory advise.</summary>
internal Func<int, CancellationToken, Task>? AdviseCoreOverride { get; set; }
private async Task AdviseSupervisoryCoreAsync(int handle, CancellationToken ct)
{
var reply = await _session!.InvokeAsync(
@@ -772,7 +772,7 @@ public class RealOpcUaClient : IOpcUaClient
// SDK 2: DataValue is a struct; restore the SDK 1.5 CLR payload shapes.
var dataValue = notification.Value;
var value = OpcUaValueBoundary.ToClr(dataValue.WrappedValue);
var timestamp = OpcUaValueBoundary.ToClrTimestamp(dataValue.SourceTimestamp);
var timestamp = OpcUaValueBoundary.EffectiveTimestamp(dataValue.SourceTimestamp, dataValue.ServerTimestamp);
var statusCode = dataValue.StatusCode.Code;
if (_callbacks.TryGetValue(handle, out var cb))
@@ -962,11 +962,29 @@ public class RealOpcUaClient : IOpcUaClient
HandleAlarmEvent(handle, sourceNodeId, efl, onTransition);
};
await _applyGate.RunAsync(async () =>
try
{
eventShard.AddItem(item);
await eventShard.ApplyChangesAsync(cancellationToken);
}, cancellationToken);
await _applyGate.RunAsync(async () =>
{
eventShard.AddItem(item);
await eventShard.ApplyChangesAsync(cancellationToken);
}, cancellationToken);
}
catch
{
await DiscardFailedAlarmItemAsync(handle, eventShard, item);
throw;
}
// DCL-3: ApplyChangesAsync does NOT throw for a per-item create failure — the server's
// verdict is on the item's status, exactly as on the data path. An unknown node, a node
// that is not an event notifier or a rejected event filter used to be recorded as a live
// feed (SubscribeAlarmsResponse Success) that never delivers anything.
if (AlarmItemCreateError(item) is { } createError)
{
await DiscardFailedAlarmItemAsync(handle, eventShard, item);
throw new ServiceResultException(createError);
}
_alarmItems[handle] = item;
// Replay currently-active conditions as a Snapshot…SnapshotComplete sequence.
@@ -974,6 +992,42 @@ public class RealOpcUaClient : IOpcUaClient
return handle;
}
/// <summary>
/// The server's per-item verdict on an alarm event monitored item after
/// <c>ApplyChangesAsync</c>: the bad <see cref="ServiceResult"/> when the create was rejected,
/// else <c>null</c> (DCL-3).
/// </summary>
internal static ServiceResult? AlarmItemCreateError(MonitoredItem item)
{
var error = item.Status?.Error;
return error != null && ServiceResult.IsBad(error) ? error : null;
}
/// <summary>
/// Unwinds a half-created alarm feed: removes the item from the event shard (best effort —
/// a dead session must not mask the original failure) and drops the per-handle bookkeeping
/// <see cref="CreateAlarmSubscriptionAsync"/> created up front.
/// </summary>
private async Task DiscardFailedAlarmItemAsync(string handle, Subscription eventShard, MonitoredItem item)
{
try
{
await _applyGate.RunAsync(async () =>
{
eventShard.RemoveItem(item);
await eventShard.ApplyChangesAsync(CancellationToken.None);
}, CancellationToken.None);
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Removing a failed alarm event item from the event shard failed (ignored).");
}
_alarmInRefresh.TryRemove(handle, out _);
_alarmSnapshotIds.TryRemove(handle, out _);
_alarmLastState.TryRemove(handle, out _);
}
/// <inheritdoc />
public async Task RemoveAlarmSubscriptionAsync(string subscriptionHandle, CancellationToken cancellationToken = default)
{
@@ -1555,7 +1609,8 @@ public class RealOpcUaClient : IOpcUaClient
var result = results[i];
outcomes[index] = new OpcUaReadOutcome(
nodeId, OpcUaValueBoundary.ToClr(result.WrappedValue),
OpcUaValueBoundary.ToClrTimestamp(result.SourceTimestamp), result.StatusCode.Code, null);
OpcUaValueBoundary.EffectiveTimestamp(result.SourceTimestamp, result.ServerTimestamp),
result.StatusCode.Code, null);
}
else
{
@@ -33,8 +33,11 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
///
/// Supervision: Resume on exception (from the Instance Actor). This actor has no children.
/// </summary>
public class AlarmActor : ReceiveActor
public class AlarmActor : ReceiveActor, IWithTimers
{
/// <inheritdoc />
public ITimerScheduler Timers { get; set; } = null!;
private readonly string _alarmName;
private readonly string _instanceName;
private readonly IActorRef _instanceActor;
@@ -171,6 +174,15 @@ public class AlarmActor : ReceiveActor
private readonly Queue<(DateTimeOffset Timestamp, double Value)> _rateOfChangeWindow = new();
private readonly TimeSpan _rateOfChangeWindowDuration;
/// <summary>
/// SRT-3: the newest sample folded into the rate window, and the wall-clock instant it was
/// processed — so the window-expiry tick can tell how far (in the samples' own time base)
/// the window has advanced since a value that has simply stopped changing.
/// </summary>
private (DateTimeOffset Timestamp, double Value, DateTimeOffset ProcessedAtUtc)? _rateLastSample;
private const string RateWindowTimerKey = "rate-window";
private int _executionCounter;
/// <summary>Initializes a new <see cref="AlarmActor"/> and configures message handlers for the alarm.</summary>
@@ -266,6 +278,9 @@ public class AlarmActor : ReceiveActor
// Handle a faulted off-dispatcher evaluation task (N2) — clears in-flight
// instead of stranding the alarm trigger with an unhandled Status.Failure.
Receive<ExpressionEvalFailed>(HandleExpressionEvalFailed);
// SRT-3: a RateOfChange window that ages out while the value holds re-evaluates.
Receive<RateWindowTick>(_ => HandleRateWindowTick());
}
/// <summary>
@@ -350,6 +365,9 @@ public class AlarmActor : ReceiveActor
};
ApplyTriggeredState(isTriggered, observedSource);
if (_triggerType == AlarmTriggerType.RateOfChange)
ScheduleRateWindowExpiry();
}
catch (Exception ex)
{
@@ -586,27 +604,9 @@ public class AlarmActor : ReceiveActor
// Add to window
_rateOfChangeWindow.Enqueue((timestamp, numericValue));
_rateLastSample = (timestamp, numericValue, DateTimeOffset.UtcNow);
// Remove old entries outside the window
var cutoff = timestamp - _rateOfChangeWindowDuration;
while (_rateOfChangeWindow.Count > 0 && _rateOfChangeWindow.Peek().Timestamp < cutoff)
{
_rateOfChangeWindow.Dequeue();
}
if (_rateOfChangeWindow.Count < 2) return false;
var oldest = _rateOfChangeWindow.Peek();
var timeDelta = (timestamp - oldest.Timestamp).TotalSeconds;
if (timeDelta <= 0) return false;
var signedRate = (numericValue - oldest.Value) / timeDelta;
return config.Direction switch
{
RateOfChangeDirection.Rising => signedRate > config.ThresholdPerSecond,
RateOfChangeDirection.Falling => -signedRate > config.ThresholdPerSecond,
_ => Math.Abs(signedRate) > config.ThresholdPerSecond
};
return EvaluateRateWindow(config, timestamp, numericValue);
}
catch
{
@@ -614,13 +614,97 @@ public class AlarmActor : ReceiveActor
}
}
/// <summary>
/// Prunes the rate window to <paramref name="now"/> and evaluates the rate from the oldest
/// surviving sample to <paramref name="currentValue"/> at <paramref name="now"/>. Fewer than two
/// samples in the window ⇒ not triggered.
/// </summary>
private bool EvaluateRateWindow(RateOfChangeEvalConfig config, DateTimeOffset now, double currentValue)
{
// Remove old entries outside the window
var cutoff = now - _rateOfChangeWindowDuration;
while (_rateOfChangeWindow.Count > 0 && _rateOfChangeWindow.Peek().Timestamp < cutoff)
{
_rateOfChangeWindow.Dequeue();
}
if (_rateOfChangeWindow.Count < 2) return false;
var oldest = _rateOfChangeWindow.Peek();
var timeDelta = (now - oldest.Timestamp).TotalSeconds;
if (timeDelta <= 0) return false;
var signedRate = (currentValue - oldest.Value) / timeDelta;
return config.Direction switch
{
RateOfChangeDirection.Rising => signedRate > config.ThresholdPerSecond,
RateOfChangeDirection.Falling => -signedRate > config.ThresholdPerSecond,
_ => Math.Abs(signedRate) > config.ThresholdPerSecond
};
}
/// <summary>
/// SRT-3 (2026-12-02 review): tag subscriptions report on CHANGE, so a value that steps and
/// then holds produces no further sample, and the window — pruned only when a sample arrived —
/// used to keep the alarm Active indefinitely although the rate had been 0 since the step.
/// While the window holds two or more samples, a single-shot tick is armed for the moment its
/// oldest sample ages out; the tick re-evaluates with the value held flat since the newest
/// sample. Each new sample re-arms it (the timer key replaces any pending tick).
/// </summary>
private void ScheduleRateWindowExpiry()
{
if (_rateOfChangeWindow.Count < 2 || _rateLastSample is not { } last)
{
Timers.Cancel(RateWindowTimerKey);
return;
}
// In the samples' own time base the oldest sample leaves the window at
// oldest + window; it was `last.Timestamp` when the newest sample was processed.
// +10 ms because the prune keeps a sample exactly AT the cutoff.
var dueIn = _rateOfChangeWindow.Peek().Timestamp + _rateOfChangeWindowDuration - last.Timestamp
- (DateTimeOffset.UtcNow - last.ProcessedAtUtc)
+ TimeSpan.FromMilliseconds(10);
if (dueIn < TimeSpan.Zero) dueIn = TimeSpan.Zero;
Timers.StartSingleTimer(RateWindowTimerKey, RateWindowTick.Instance, dueIn);
}
private void HandleRateWindowTick()
{
if (_evalConfig is not RateOfChangeEvalConfig config || _rateLastSample is not { } last)
return;
try
{
// "Now" in the samples' time base: the newest sample's timestamp advanced by the wall
// time since it was processed. The value has been flat at last.Value since then.
var now = last.Timestamp + (DateTimeOffset.UtcNow - last.ProcessedAtUtc);
ApplyTriggeredState(EvaluateRateWindow(config, now, last.Value), sourceExecutionId: null);
ScheduleRateWindowExpiry();
}
catch (Exception ex)
{
_healthCollector?.IncrementAlarmError();
_logger.LogError(ex, "Alarm {Alarm} rate-window re-evaluation error on {Instance}", _alarmName, _instanceName);
}
}
/// <summary>SRT-3: the RateOfChange window-expiry tick.</summary>
internal sealed class RateWindowTick
{
public static readonly RateWindowTick Instance = new();
private RateWindowTick() { }
}
/// <summary>
/// Evaluates the compiled trigger expression against the current attribute
/// snapshot, returning the resulting bool. This bool feeds the existing
/// binary Normal↔Active state path — the alarm is active while true. A
/// throwing, non-bool, or timed-out expression is treated as false (logged
/// as an alarm error) so that the state machine still runs — an Active
/// alarm correctly clears if the expression starts throwing.
/// non-bool result is an evaluated false. A THROWING or TIMED-OUT evaluation
/// is "unknown", not false (2026-12-02 review SRT-2): it is logged (node log,
/// alarm-error counter, a rate-limited site event) and the alarm KEEPS its
/// current state. Coercing it to false cleared an Active alarm on a single slow
/// evaluation under load, then re-raised it — with a second on-trigger run — on
/// the next successful one, for a condition that never cleared.
/// </summary>
private void StartExpressionEvaluation()
{
@@ -656,7 +740,7 @@ public class AlarmActor : ReceiveActor
// compile-checked pre-deploy.
var state = await expression.RunAsync(
new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token);
return state.ReturnValue is bool b && b;
return (bool?)(state.ReturnValue is bool b && b);
}
finally
{
@@ -666,14 +750,11 @@ public class AlarmActor : ReceiveActor
catch (Exception ex)
{
// OperationCanceledException (timeout, INCLUDING one that fired while still
// waiting on the gate) falls through here too and is treated as false.
// _healthCollector (Interlocked) and _logger are thread-safe, so this catch
// is safe off the actor thread.
_healthCollector?.IncrementAlarmError();
_logger.LogError(ex,
"Alarm {Alarm} trigger expression evaluation failed on {Instance}; treated as false",
_alarmName, _instanceName);
return false;
// waiting on the gate) falls through here too. The outcome is UNKNOWN (null),
// never false (SRT-2). ReportEvalError touches only thread-safe members, so this
// catch is safe off the actor thread.
ReportEvalError(ex);
return null;
}
finally
{
@@ -694,7 +775,9 @@ public class AlarmActor : ReceiveActor
_evalInFlight = false;
try
{
ApplyTriggeredState(msg.Result, msg.SourceExecutionId);
// Unknown (the evaluation threw or timed out): keep the current state (SRT-2).
if (msg.Result is { } result)
ApplyTriggeredState(result, msg.SourceExecutionId);
}
catch (Exception ex)
{
@@ -708,18 +791,37 @@ public class AlarmActor : ReceiveActor
/// <summary>
/// Applies a faulted off-dispatcher evaluation task (N2): logs the fault, then
/// delegates to the false result (per the class contract — a throwing expression
/// is treated as false so the state machine still runs, an Active alarm clears)
/// which clears in-flight and drains any pending evaluation. Without this the
/// alarm trigger would be permanently parked with _evalInFlight stuck true.
/// delegates to the UNKNOWN result (SRT-2 — the alarm keeps its state), which clears
/// in-flight and drains any pending evaluation. Without this the alarm trigger would
/// be permanently parked with _evalInFlight stuck true.
/// </summary>
private void HandleExpressionEvalFailed(ExpressionEvalFailed msg)
{
ReportEvalError(msg.Cause);
HandleExpressionEvalResult(new ExpressionEvalResult(null, msg.SourceExecutionId));
}
/// <summary>One "evaluation failed" site event per minute per alarm (SRT-2).</summary>
private readonly EventRateLimiter _evalErrorEvents = new(TimeSpan.FromMinutes(1));
/// <summary>
/// Records a failed/timed-out trigger-expression evaluation: alarm-error counter and node log
/// every time, a <c>site_events</c> Warning at most once a minute. Thread-safe (called from the
/// off-dispatcher evaluation task).
/// </summary>
private void ReportEvalError(Exception ex)
{
_healthCollector?.IncrementAlarmError();
_logger.LogError(msg.Cause,
"Alarm {Alarm} trigger-expression evaluation task faulted on {Instance}; treated as false",
_logger.LogError(ex,
"Alarm {Alarm} trigger expression evaluation failed on {Instance}; alarm state unchanged",
_alarmName, _instanceName);
HandleExpressionEvalResult(new ExpressionEvalResult(false, msg.SourceExecutionId));
if (_evalErrorEvents.TryAcquire(out var suppressed))
{
var note = suppressed > 0 ? $" ({suppressed} more failure(s) since the last event)" : string.Empty;
LogAlarmEvent("Warning",
$"Alarm '{_alarmName}' on '{_instanceName}': trigger expression could not be evaluated " +
$"({ex.GetType().Name}: {ex.Message}); alarm state left unchanged{note}");
}
}
/// <summary>
@@ -1032,7 +1134,9 @@ public class AlarmActor : ReceiveActor
/// to the execution that actually wrote the value it evaluated — not to a
/// later change that arrived while the evaluation was in flight.
/// </summary>
private sealed record ExpressionEvalResult(bool Result, Guid? SourceExecutionId = null);
/// <param name="Result">The truth value, or null when the evaluation threw or timed out (SRT-2: keep state).</param>
/// <param name="SourceExecutionId">Writer of the newest value in the evaluated snapshot.</param>
private sealed record ExpressionEvalResult(bool? Result, Guid? SourceExecutionId = null);
/// <summary>
/// Piped back to self when the off-dispatcher evaluation TASK itself faults
@@ -3423,7 +3423,14 @@ public class DeploymentManagerActor : ReceiveActor, IWithTimers
// Flow Debugger (design 2026-09-05 §5.2): the trace flag rides beside the parent id.
Trace: request.Trace);
var sender = Sender;
instanceActor.Ask<ScriptCallResult>(scriptCall, TimeSpan.FromSeconds(30))
// SRT-13: wait as long as the TARGET SCRIPT may run — its resolved execution timeout
// (enqueue-anchored, so the run replies by then even if it queued) plus the
// stuck-script grace and a small margin — not a hard-coded 30 s. A 120 s handshake
// script used to fail its inbound caller at 30 s while it ran on and completed its
// device writes, so a retrying caller ran the handshake twice.
RoutedCallTimeoutAsync(instanceActor, request.ScriptName)
.ContinueWith(timeout => instanceActor.Ask<ScriptCallResult>(scriptCall, timeout.Result))
.Unwrap()
.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
@@ -3466,6 +3473,30 @@ public class DeploymentManagerActor : ReceiveActor, IWithTimers
}
}
/// <summary>Slack on top of a routed script's own timeout before the routed Ask gives up.</summary>
internal static readonly TimeSpan RoutedCallMargin = TimeSpan.FromSeconds(5);
/// <summary>
/// SRT-13: the routed-call Ask timeout for <paramref name="scriptName"/> — its resolved execution
/// timeout plus the stuck-script grace and <see cref="RoutedCallMargin"/>. Falls back to the
/// site default timeout when the instance cannot answer (never faults).
/// </summary>
private Task<TimeSpan> RoutedCallTimeoutAsync(IActorRef instanceActor, string scriptName) =>
RoutedCallTimeoutAsync(instanceActor, scriptName, _options);
/// <inheritdoc cref="RoutedCallTimeoutAsync(IActorRef, string)"/>
internal static Task<TimeSpan> RoutedCallTimeoutAsync(IActorRef instanceActor, string scriptName, SiteRuntimeOptions options)
{
var slack = TimeSpan.FromMilliseconds(Math.Max(0, options.StuckScriptGraceMs)) + RoutedCallMargin;
var fallback = TimeSpan.FromSeconds(options.ScriptExecutionTimeoutSeconds) + slack;
return instanceActor
.Ask<InstanceActor.ScriptExecutionTimeoutReply>(
new InstanceActor.GetScriptExecutionTimeout(scriptName), TimeSpan.FromSeconds(5))
.ContinueWith(t => t.IsCompletedSuccessfully && t.Result.Timeout is { } scriptTimeout
? scriptTimeout + slack
: fallback, TaskScheduler.Default);
}
/// <summary>
/// Projects a routed script's return value to a cross-process-serializable plain
/// CLR graph (<see cref="Dictionary{TKey,TValue}"/> / <see cref="List{T}"/> /
@@ -0,0 +1,39 @@
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
/// <summary>
/// Thread-safe "at most one per interval" gate for an operational site event that a failure
/// path could otherwise emit on every occurrence — e.g. a trigger expression that times out on
/// every attribute change during a burst (2026-12-02 review SRT-2). The node log and the health
/// counter still record every occurrence; only the <c>site_events</c> row is rate-limited.
/// </summary>
internal sealed class EventRateLimiter
{
private readonly long _intervalMs;
private long _nextAllowedMs = long.MinValue;
private int _suppressed;
/// <summary>Creates a limiter that admits one event per <paramref name="interval"/>.</summary>
/// <param name="interval">Minimum spacing between admitted events.</param>
public EventRateLimiter(TimeSpan interval) => _intervalMs = (long)interval.TotalMilliseconds;
/// <summary>
/// True when an event may be emitted now; the caller then emits it, naming
/// <paramref name="suppressedSinceLast"/> occurrences that were dropped since the previous one.
/// </summary>
/// <param name="suppressedSinceLast">Occurrences suppressed since the last admitted event.</param>
/// <returns>Whether the event is admitted.</returns>
public bool TryAcquire(out int suppressedSinceLast)
{
var now = Environment.TickCount64;
var next = Interlocked.Read(ref _nextAllowedMs);
if (now >= next && Interlocked.CompareExchange(ref _nextAllowedMs, now + _intervalMs, next) == next)
{
suppressedSinceLast = Interlocked.Exchange(ref _suppressed, 0);
return true;
}
Interlocked.Increment(ref _suppressed);
suppressedSinceLast = 0;
return false;
}
}
@@ -153,6 +153,16 @@ public class InstanceActor : ReceiveActor
internal sealed record StaticOverridesFlushed(IActorRef Actor, Exception? Error);
/// <summary>
/// SRT-13: asks for a script's resolved execution timeout (per-script override, else the
/// site default) so a routed inbound call waits as long as the script is allowed to run
/// instead of a hard-coded 30 s.
/// </summary>
internal sealed record GetScriptExecutionTimeout(string ScriptName);
/// <summary>Reply to <see cref="GetScriptExecutionTimeout"/>; null when the script is unknown.</summary>
internal sealed record ScriptExecutionTimeoutReply(TimeSpan? Timeout);
/// <summary>
/// Cached string forms of <see cref="QualityCode"/> — the TagValueUpdate ingest path calls this once or twice per update, so a
/// static lookup replaces repeated <see cref="Enum.ToString()"/> reflection.
@@ -329,6 +339,16 @@ public class InstanceActor : ReceiveActor
// Defaults to 100 ms, mirroring NativeAlarmActor's persistFlushInterval (P4).
_staticOverrideFlushInterval = staticOverrideFlushInterval ?? TimeSpan.FromMilliseconds(100);
_staticStateResetGate = staticStateResetGate;
// SRT-12: the first static-override flush is ordered AFTER the redeploy reset. A value
// script on the new instance can write a static attribute within the first ~100 ms; its
// flush ran on its own connection with no ordering against the (slower, lock-contended)
// clear, so the clear could land afterwards and delete it — in memory but not on disk,
// silently reverted by the next restart. The reset's own fault is ignored here (the
// deploy fails on it through its persistence join).
if (staticStateResetGate != null)
_staticOverridePersistTail = staticStateResetGate.ContinueWith(
static _ => { }, CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
_configuration = configuration;
@@ -391,6 +411,7 @@ public class InstanceActor : ReceiveActor
// Handle script call requests — route to appropriate Script Actor (Ask pattern)
Receive<ScriptCallRequest>(HandleScriptCallRequest);
Receive<GetScriptExecutionTimeout>(HandleGetScriptExecutionTimeout);
// Handle attribute value changes from DCL (Tell pattern)
Receive<AttributeValueChanged>(HandleAttributeValueChanged);
@@ -769,6 +790,15 @@ public class InstanceActor : ReceiveActor
if (!_overridesLoaded)
_staticWritesBeforeOverrideLoad.Add(command.AttributeName);
// SRT-11: a successful write refreshes the stored quality and timestamp with the value.
// A List attribute loaded Bad (malformed default/override) used to stay Bad for the
// actor's lifetime — GetAttribute, the Debug View snapshot and a requireGoodQuality
// waiter all saw Bad while the stream said Good — and a static attribute had no stored
// timestamp at all, so every snapshot stamped it "now".
var writtenAt = DateTimeOffset.UtcNow;
_attributeQualities[command.AttributeName] = "Good";
_attributeTimestamps[command.AttributeName] = writtenAt;
// Publish attribute change to stream and notify children
var changed = new AttributeValueChanged(
_instanceUniqueName,
@@ -776,7 +806,7 @@ public class InstanceActor : ReceiveActor
command.AttributeName,
command.Value,
"Good",
DateTimeOffset.UtcNow,
writtenAt,
// (ParentExecutionId tag-cascade): carry the writing
// execution's id onto the change so a child Alarm Actor this write
// trips can chain its on-trigger script run under the writer. Null for
@@ -1077,6 +1107,32 @@ public class InstanceActor : ReceiveActor
/// Routes script call requests to the appropriate Script Actor.
/// Uses Ask pattern.
/// </summary>
/// <summary>
/// SRT-12: the native-alarm rehydration read, chained behind <see cref="_staticStateResetGate"/>
/// when this start is a (re)deploy; null (the actor reads directly) on every other start.
/// </summary>
private Task<IReadOnlyList<NativeAlarmRow>>? GatedNativeAlarmRead(string sourceCanonicalName)
{
if (_staticStateResetGate == null)
return null;
var storage = _storage;
var instanceName = _instanceUniqueName;
return _staticStateResetGate
.ContinueWith(_ => storage.GetNativeAlarmsAsync(instanceName, sourceCanonicalName),
CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default)
.Unwrap();
}
private void HandleGetScriptExecutionTimeout(GetScriptExecutionTimeout request)
{
var script = _configuration?.Scripts.FirstOrDefault(s => s.CanonicalName == request.ScriptName);
Sender.Tell(new ScriptExecutionTimeoutReply(script is null
? null
: TimeSpan.FromSeconds(script.ExecutionTimeoutSeconds is { } perScript && perScript > 0
? perScript
: _options.ScriptExecutionTimeoutSeconds)));
}
private void HandleScriptCallRequest(ScriptCallRequest request)
{
if (_scriptActors.TryGetValue(request.ScriptName, out var scriptActor))
@@ -1415,11 +1471,16 @@ public class InstanceActor : ReceiveActor
private void HandleConnectionQualityChanged(ConnectionQualityChanged qualityChanged)
{
_logger.LogWarning("Connection {Connection} quality changed to {Quality} for instance {Instance}",
qualityChanged.ConnectionName, qualityChanged.Quality, _instanceUniqueName);
if (qualityChanged.Quality == QualityCode.Good)
_logger.LogInformation("Connection {Connection} restored for instance {Instance}",
qualityChanged.ConnectionName, _instanceUniqueName);
else
_logger.LogWarning("Connection {Connection} quality changed to {Quality} for instance {Instance}",
qualityChanged.ConnectionName, qualityChanged.Quality, _instanceUniqueName);
// Lever 1 (2026-08-28): a connection returning to Good is the Instance Actor's
// only restore signal (the DCL re-subscribes transparently). If our own subscribe
// only restore signal (the DCL re-subscribes transparently; it sends Good when the
// connection re-enters Connected — SRT-6, WP3 task 3.8). If our own subscribe
// on it is still unconfirmed, retry at the floor now rather than in up to
// TagSubscribeRetryMaxIntervalMs — recovery must be prompt. Timer != null ⇔ the
// subscribe is unconfirmed (it is only nulled by a Success); if a request is in
@@ -1436,6 +1497,12 @@ public class InstanceActor : ReceiveActor
ArmTagSubscribeWatchdog(qualityChanged.ConnectionName, subState);
}
// Good is a restore signal ONLY (decided 2026-12-03, SRT-6): it must NOT stamp the
// bound attributes Good with their last-known values — those values are from before
// the outage, and the device has not re-reported yet. Per-tag quality comes back
// through the DCL's re-subscribe and re-seed as ordinary TagValueUpdates.
if (qualityChanged.Quality == QualityCode.Good) return;
if (_configuration == null) return;
// Mark all attributes bound to this connection with the new quality
@@ -2297,6 +2364,11 @@ public class InstanceActor : ReceiveActor
}
var nativeKind = ResolveNativeKind(nativeSource.ConnectionName);
// SRT-12: on a (re)deploy the native-alarm rehydration read is chained behind the
// reset gate too — not only the override load — so the successor can only observe the
// CLEARED native_alarm_state, never re-emit the predecessor's conditions (stale alarms
// from an old binding that no snapshot would ever reconcile if the source is down).
var rehydrationRead = GatedNativeAlarmRead(nativeSource.CanonicalName);
var props = Props.Create(() => new NativeAlarmActor(
nativeSource,
_instanceUniqueName,
@@ -2306,7 +2378,9 @@ public class InstanceActor : ReceiveActor
_options,
_logger,
nativeKind,
_serviceProvider));
_serviceProvider,
null,
rehydrationRead));
var actorRef = TryCreateChild(
props, $"native-alarm-{nativeSource.CanonicalName}", "Native alarm source", nativeSource.CanonicalName);
@@ -366,7 +366,8 @@ public class ScriptActor : ReceiveActor, IWithTimers
/// to date — a Conditional's truth value, an Expression's last result (evaluated, never fired) —
/// so the NEXT real change is judged against the real value: no spurious edge from the replay,
/// and no missed edge afterwards. A WhileTrue trigger whose condition already holds is seeded
/// true without starting its re-fire timer; it fires on its next false→true edge.
/// true WITH its re-fire timer running but without the immediate edge run (2026-12-02 review
/// SRT-4 — it used to lose its periodic re-fire until the condition went false and back).
/// </summary>
private void HandleAttributeValueSeed(Messages.AttributeValueSeed seed)
{
@@ -376,7 +377,10 @@ public class ScriptActor : ReceiveActor, IWithTimers
if (_triggerConfig is ConditionalTriggerConfig conditional &&
conditional.AttributeName == changed.AttributeName)
{
_conditionState = EvaluateCondition(conditional, changed.Value);
var seeded = EvaluateCondition(conditional, changed.Value);
if (conditional.Mode == TriggerMode.WhileTrue)
AdoptWhileTrueFromSeed(seeded, _conditionState);
_conditionState = seeded;
}
else if (_triggerConfig is ExpressionTriggerConfig)
{
@@ -441,7 +445,7 @@ public class ScriptActor : ReceiveActor, IWithTimers
// compile-checked pre-deploy.
var state = await expression.RunAsync(
new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token);
return state.ReturnValue is bool b && b;
return (bool?)(state.ReturnValue is bool b && b);
}
finally
{
@@ -451,12 +455,15 @@ public class ScriptActor : ReceiveActor, IWithTimers
catch (Exception ex)
{
// OperationCanceledException (timeout, INCLUDING a timeout that fired while
// still waiting on the gate) falls through here too and is treated as false.
// still waiting on the gate) falls through here too. The outcome is UNKNOWN
// (null), never false (2026-12-02 review SRT-2): coercing it to false stopped a
// WhileTrue timer / re-armed an OnTrue edge, so the next successful evaluation
// fired an extra run for a condition that never went false.
// LogExpressionError touches only thread-safe members (_healthCollector
// Interlocked, _logger, DI-resolved singleton logger) so it is safe off the
// actor thread.
// Interlocked, _logger, DI-resolved singleton logger, the rate limiter) so it is
// safe off the actor thread.
LogExpressionError(ex);
return false;
return null;
}
finally
{
@@ -476,17 +483,22 @@ public class ScriptActor : ReceiveActor, IWithTimers
private void HandleExpressionEvalResult(ExpressionEvalResult msg)
{
_evalInFlight = false;
if (_triggerConfig is ExpressionTriggerConfig exprConfig)
// Unknown (the evaluation threw or timed out): adopt nothing, fire nothing (SRT-2).
if (_triggerConfig is ExpressionTriggerConfig exprConfig && msg.Result is { } result)
{
if (msg.SeedOnly)
{
// 01/SR-U1: a seed adopts the truth value and never fires.
// 01/SR-U1: a seed adopts the truth value and never fires — but a WhileTrue
// trigger it leaves true keeps re-firing on its cadence (SRT-4), exactly as it
// did before the restart that made this a seed.
if (exprConfig.Mode == TriggerMode.WhileTrue)
AdoptWhileTrueFromSeed(result, _lastExpressionResult);
}
else if (exprConfig.Mode == TriggerMode.WhileTrue)
HandleWhileTrueTransition(msg.Result, _lastExpressionResult);
else if (msg.Result && !_lastExpressionResult)
HandleWhileTrueTransition(result, _lastExpressionResult);
else if (result && !_lastExpressionResult)
TrySpawnExecution(null);
_lastExpressionResult = msg.Result;
_lastExpressionResult = result;
}
if (_evalPending)
{
@@ -497,29 +509,34 @@ public class ScriptActor : ReceiveActor, IWithTimers
/// <summary>
/// Applies a faulted off-dispatcher evaluation task (N2): logs the fault via the
/// existing error path (which also increments the health counter), then reuses the
/// false-result path — clearing in-flight, applying the false edge, and draining any
/// pending evaluation — so a transient scheduler fault cannot permanently park the trigger.
/// A faulted SEED evaluation (review 2026-10-21 follow-up L4) carries no truth value at all:
/// it only clears in-flight and drains the pending evaluation, adopting nothing — replaying it
/// as a real false stopped a running WhileTrue timer, and even as a seeded false it would make
/// the next true evaluation look like a fresh edge and fire spuriously.
/// existing error path (which also increments the health counter), then clears in-flight
/// and drains any pending evaluation, so a transient scheduler fault cannot permanently
/// park the trigger. A faulted evaluation carries no truth value at all and adopts nothing
/// (review 2026-10-21 follow-up L4 for seeds; 2026-12-02 review SRT-2 for real changes) —
/// replaying it as a false stopped a running WhileTrue timer, and made the next true
/// evaluation look like a fresh edge and fire spuriously.
/// </summary>
private void HandleExpressionEvalFailed(ExpressionEvalFailed msg)
{
// A faulted evaluation — seed or real — carries no truth value: clear in-flight, drain
// the pending evaluation, adopt nothing (SRT-2; the seed case was already so, L4).
LogExpressionError(msg.Cause);
if (!msg.SeedOnly)
{
HandleExpressionEvalResult(new ExpressionEvalResult(false));
return;
}
HandleExpressionEvalResult(new ExpressionEvalResult(null, msg.SeedOnly));
}
_evalInFlight = false;
if (_evalPending)
{
_evalPending = false;
StartExpressionEvaluation(_evalPendingSeedOnly);
}
/// <summary>
/// SRT-4 (2026-12-02 review): a seed that leaves a WhileTrue trigger's condition TRUE starts
/// the periodic re-fire timer WITHOUT the immediate edge run (a seed never fires — 01/SR-U1);
/// one that leaves it false stops it. Before this, a WhileTrue script whose condition was
/// adopted from a persisted static override (failover, restart, disable/enable) never
/// re-fired again until the condition went false and back to true.
/// </summary>
private void AdoptWhileTrueFromSeed(bool nowTrue, bool wasTrue)
{
if (nowTrue && !wasTrue)
StartWhileTrueTimer();
else if (!nowTrue && wasTrue)
StopWhileTrueTimer();
}
/// <summary>
@@ -586,13 +603,23 @@ public class ScriptActor : ReceiveActor, IWithTimers
private void LogExpressionError(Exception ex)
{
_healthCollector?.IncrementScriptError();
var errorMsg = $"Trigger expression for script '{_scriptName}' on instance '{_instanceName}' failed: {ex.Message}";
_logger.LogError(ex, "Trigger expression evaluation failed: {Script} on {Instance}", _scriptName, _instanceName);
_logger.LogError(ex, "Trigger expression evaluation failed: {Script} on {Instance}; trigger state unchanged",
_scriptName, _instanceName);
// The site_events row is rate-limited (SRT-2): a burst that times out every evaluation
// would otherwise mint one Error row per attribute change.
if (!_evalErrorEvents.TryAcquire(out var suppressed))
return;
var note = suppressed > 0 ? $" ({suppressed} more failure(s) since the last event)" : string.Empty;
var errorMsg = $"Trigger expression for script '{_scriptName}' on instance '{_instanceName}' failed: {ex.Message}; " +
$"trigger state left unchanged{note}";
_ = _serviceProvider?.GetService<ISiteEventLogger>()?.LogEventAsync(
"script", "Error", _instanceName, $"ScriptActor:{_scriptName}", errorMsg, ex.ToString());
}
/// <summary>One "trigger expression failed" site event per minute per script (SRT-2).</summary>
private readonly EventRateLimiter _evalErrorEvents = new(TimeSpan.FromMinutes(1));
/// <summary>
/// Attempts to spawn a script execution, respecting MinTimeBetweenRuns.
/// </summary>
@@ -952,7 +979,9 @@ public class ScriptActor : ReceiveActor, IWithTimers
/// carries the boolean truth value so the OnTrue/WhileTrue edge logic runs on
/// the actor thread.
/// </summary>
private sealed record ExpressionEvalResult(bool Result, bool SeedOnly = false);
/// <param name="Result">The truth value, or null when the evaluation threw or timed out (SRT-2: adopt nothing).</param>
/// <param name="SeedOnly">Whether this evaluation only seeds the edge state (01/SR-U1).</param>
private sealed record ExpressionEvalResult(bool? Result, bool SeedOnly = false);
/// <summary>
/// Piped back to self when the off-dispatcher evaluation TASK itself faults
@@ -281,18 +281,16 @@ internal static class ScriptRunLauncher
var emitPerRunEvents = ScriptRunEventPolicy.ShouldEmitPerRun(effectiveOptions, instanceName, scriptName);
var runStopwatch = Stopwatch.StartNew();
// Identify the worker this body is holding, so the watchdog can detach and
// replace it if the body wedges. Read in the FIRST synchronous segment — a script
// that later hops threads on an await no longer holds this worker, and the run-stamp
// guard in TryDetachWorker will (correctly) refuse to detach it.
var workerSlot = ScriptExecutionScheduler.CurrentWorkerSlot;
var workerRunStamp = workerSlot is { } slot ? executionScheduler.CurrentRunStamp(slot) : 0L;
// Track the worker this body is holding — not just in this first segment but after
// every await (SRT-1): each continuation runs on whichever worker dequeues it, under a
// new run stamp, so the watchdog reads the LATEST (slot, stamp) when it fires.
var workerTracker = ScriptRunWorkerTracker.Begin(executionScheduler);
IDisposable? logScope = null;
var completed = 0;
ArmStuckScriptWatchdog(
cts, options, logger, siteEventLogger, executionScheduler,
workerSlot, workerRunStamp, timeout,
workerTracker, timeout,
() => Volatile.Read(ref completed) != 0,
$"Script '{scriptName}' on instance '{instanceName}'",
instanceName, $"ScriptActor:{scriptName}");
@@ -480,7 +478,11 @@ internal static class ScriptRunLauncher
// Notify the owning ScriptActor of completion (also releases its in-flight slot).
completionTarget.Tell(new ScriptActor.ScriptExecutionCompleted(scriptName, true, null));
}
catch (OperationCanceledException)
// Only the run's OWN deadline is a timeout (SRT-10). Any other cancellation — an HTTP
// client's internal timeout, a script's own CancellationTokenSource, a cancelled read —
// falls through to the general failure path below with its real exception and stack,
// instead of being reported as "timed out after N s" for a run that lasted 5 s.
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
healthCollector?.IncrementScriptError();
summaryRecorder?.RecordTimedOut(instanceName, scriptName, runStopwatch.ElapsedMilliseconds);
@@ -714,18 +716,16 @@ internal static class ScriptRunLauncher
var scriptName = $"AlarmActor:{alarmName}";
var runStopwatch = Stopwatch.StartNew();
// Identify the worker this body is holding, so the
// stuck-script watchdog can detach and replace it if the body wedges — same
// mechanism, same gauge, as the instance-script path. Read in the FIRST synchronous
// segment, before any await.
var workerSlot = ScriptExecutionScheduler.CurrentWorkerSlot;
var workerRunStamp = workerSlot is { } slot ? executionScheduler.CurrentRunStamp(slot) : 0L;
// Track the worker this body is holding, so the stuck-script watchdog can detach and
// replace it if the body wedges — same mechanism, same gauge, as the instance-script
// path, and likewise followed across awaits (SRT-1).
var workerTracker = ScriptRunWorkerTracker.Begin(executionScheduler);
IDisposable? logScope = null;
var completed = 0;
ArmStuckScriptWatchdog(
cts, options, logger, siteEventLogger, executionScheduler,
workerSlot, workerRunStamp, timeout,
workerTracker, timeout,
() => Volatile.Read(ref completed) != 0,
$"Alarm on-trigger script for '{alarmName}' on instance '{instanceName}'",
instanceName, scriptName);
@@ -802,7 +802,8 @@ internal static class ScriptRunLauncher
summaryRecorder?.RecordCompleted(instanceName, scriptName, runStopwatch.ElapsedMilliseconds);
completionTarget.Tell(new AlarmActor.AlarmExecutionCompleted(alarmName, true));
}
catch (OperationCanceledException)
// Only the run's own deadline is a timeout (SRT-10); see RunScriptAsync.
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
healthCollector?.IncrementScriptError();
summaryRecorder?.RecordTimedOut(instanceName, scriptName, runStopwatch.ElapsedMilliseconds);
@@ -854,8 +855,7 @@ internal static class ScriptRunLauncher
ILogger logger,
ISiteEventLogger? siteEventLogger,
ScriptExecutionScheduler scheduler,
int? workerSlot,
long workerRunStamp,
ScriptRunWorkerTracker workerTracker,
TimeSpan timeout,
Func<bool> isCompleted,
string subject,
@@ -871,6 +871,8 @@ internal static class ScriptRunLauncher
var stuckMsg = $"{subject} exceeded its {timeout.TotalSeconds:F0}s timeout and is STILL EXECUTING — " +
"its dedicated script-execution thread is blocked (cooperative cancellation not observed).";
// The worker the run holds NOW — after any number of awaits (SRT-1).
var (workerSlot, workerRunStamp) = workerTracker.Snapshot();
var outcome = workerSlot is { } slot
? scheduler.TryDetachWorker(slot, workerRunStamp)
: WorkerDetachOutcome.NotRunning;
@@ -0,0 +1,111 @@
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
/// <summary>
/// Tracks WHICH script-execution worker a run is holding right now, for the stuck-script
/// watchdog (2026-12-02 review SRT-1).
/// <para>
/// The launcher used to capture <c>(slot, runStamp)</c> once, in the run's first synchronous
/// segment. But a script's <c>await</c> continuation is a NEW task queued back onto the scheduler,
/// dequeued by whichever worker is free under a NEW run stamp — so once the script had awaited
/// anything (practically every script reads an attribute before doing I/O), the watchdog's
/// captured pair no longer matched, <c>TryDetachWorker</c> answered <c>NotRunning</c>, and a
/// worker wedged in blocking I/O was never detached or replaced.
/// </para>
/// <para>
/// The run's tracker flows with its <see cref="ExecutionContext"/> through an
/// <see cref="AsyncLocal{T}"/> whose change callback fires every time a piece of the run starts
/// (context restored on a thread) or stops (context reverted) executing. On start it records the
/// current thread's worker slot and that worker's current run stamp; on stop it clears them if
/// that worker was the recorded one. A run blocked inside a continuation therefore keeps the
/// latest <c>(slot, stamp)</c> of the worker it is actually blocking, while a run parked in an
/// await (holding no thread) reads as "not on a worker".
/// </para>
/// </summary>
internal sealed class ScriptRunWorkerTracker
{
private static readonly AsyncLocal<ScriptRunWorkerTracker?> Current = new(OnContextChanged);
private readonly ScriptExecutionScheduler _scheduler;
private readonly object _gate = new();
private int _slot = -1;
private long _stamp;
private ScriptRunWorkerTracker(ScriptExecutionScheduler scheduler) => _scheduler = scheduler;
/// <summary>
/// Starts tracking the calling run: records the worker the caller is on (if any) and installs
/// the tracker in the run's execution context so every later continuation updates it. Call in
/// the run's first synchronous segment.
/// </summary>
/// <param name="scheduler">The scheduler whose workers run this script.</param>
/// <returns>The run's tracker.</returns>
public static ScriptRunWorkerTracker Begin(ScriptExecutionScheduler scheduler)
{
var tracker = new ScriptRunWorkerTracker(scheduler);
tracker.OnEnter();
Current.Value = tracker;
return tracker;
}
/// <summary>
/// The worker the run is executing on right now, as <c>(slot, runStamp)</c>; a null slot when
/// the run holds no script-execution worker (parked in an await, or on another thread).
/// </summary>
/// <returns>The latest observed worker slot and its run stamp.</returns>
public (int? Slot, long RunStamp) Snapshot()
{
lock (_gate)
return _slot >= 0 ? (_slot, _stamp) : (null, 0L);
}
private static void OnContextChanged(AsyncLocalValueChangedArgs<ScriptRunWorkerTracker?> args)
{
// Only thread switches matter; the explicit set in Begin already recorded the worker.
if (!args.ThreadContextChanged)
return;
try
{
if (args.PreviousValue is { } leaving && !ReferenceEquals(leaving, args.CurrentValue))
leaving.OnLeave();
if (args.CurrentValue is { } entering && !ReferenceEquals(entering, args.PreviousValue))
entering.OnEnter();
}
catch
{
// Never let diagnostics bookkeeping fault an execution-context switch.
}
}
private void OnEnter()
{
// Only a script-execution worker is recorded. The run's execution context also flows to
// threads that hold no worker — a thread-pool continuation, or the watchdog's own
// timer callback, which captured the context when it was registered — and those must
// NOT erase the worker a still-running segment is blocking. A stale record is harmless:
// OnLeave clears it when that worker's segment ends, and TryDetachWorker re-checks the
// run stamp before detaching anything.
if (ScriptExecutionScheduler.CurrentWorkerSlot is not { } slot)
return;
var stamp = _scheduler.CurrentRunStamp(slot);
if (stamp == 0)
return;
lock (_gate)
{
_slot = slot;
_stamp = stamp;
}
}
private void OnLeave()
{
var slot = ScriptExecutionScheduler.CurrentWorkerSlot;
lock (_gate)
{
if (slot is { } s && s == _slot)
{
_slot = -1;
_stamp = 0;
}
}
}
}
@@ -728,7 +728,10 @@ public class ScriptRuntimeContext
// ScadaBridge#56: the Instance Actor logs under this run's id while serving it.
SourceExecutionId: _executionId);
var response = await _instanceActor.Ask<GetAttributeResponse>(request, _askTimeout).ConfigureAwait(false);
// SRT-9: the run's deadline token cancels the wait, so a run parked here takes the timeout
// path at its deadline instead of sailing past it (Roslyn only observes the token between
// top-level statements).
var response = await _instanceActor.Ask<GetAttributeResponse>(request, _askTimeout, _scriptTimeoutToken).ConfigureAwait(false);
if (!response.Found)
{
@@ -940,7 +943,8 @@ public class ScriptRuntimeContext
{
// Ask — mutation serialized through the Instance Actor mailbox; the reply
// carries the device-write outcome for data-connected attributes.
response = await _instanceActor.Ask<SetStaticAttributeResponse>(command, _askTimeout).ConfigureAwait(false);
// SRT-9: bounded by the run's deadline too (a data-sourced write waits out the DCL Ask).
response = await _instanceActor.Ask<SetStaticAttributeResponse>(command, _askTimeout, _scriptTimeoutToken).ConfigureAwait(false);
}
catch (Exception ex) when (sw is not null)
{
@@ -1217,7 +1221,9 @@ public class ScriptRuntimeContext
Trace: _isTraced);
// Ask the Instance Actor, which routes to the appropriate Script Actor
var result = await _instanceActor.Ask<ScriptCallResult>(request, _askTimeout).ConfigureAwait(false);
// SRT-9: the CALLER's deadline cancels the wait — a nested script that outlives the caller's
// budget no longer lets the caller carry on past its timeout and be recorded as completed.
var result = await _instanceActor.Ask<ScriptCallResult>(request, _askTimeout, _scriptTimeoutToken).ConfigureAwait(false);
if (!result.Success)
{
@@ -1313,7 +1319,9 @@ public class ScriptRuntimeContext
// threaded so NotifyTarget.Send can stamp it onto NotificationSubmit.
_sourceNode,
// Flow Debugger: the NotifySend row rides the inline collector (null when untraced).
traceSink: _traceSink);
traceSink: _traceSink,
// SRT-8: Notify.Status's central query is bounded by the run's deadline.
scriptTimeoutToken: _scriptTimeoutToken);
/// <summary>
/// Read-only access to the instance's CURRENT alarm conditions (MES alarm-status API
@@ -2678,6 +2686,16 @@ public class ScriptRuntimeContext
private readonly TimeSpan _askTimeout;
private readonly ILogger _logger;
/// <summary>SRT-8: the run's deadline; cancels the central status query.</summary>
private readonly CancellationToken _scriptTimeoutToken;
/// <summary>
/// SRT-8: ceiling on the central round trip of <see cref="Status"/> — it is a point read,
/// and the script's whole execution budget (<c>_askTimeout</c>) is far too long to wait
/// when central is unreachable.
/// </summary>
internal static readonly TimeSpan CentralStatusQueryTimeout = TimeSpan.FromSeconds(10);
/// <summary>
/// The per-execution id for this script run, stamped
/// into <c>AuditEvent.ExecutionId</c> on the <c>NotifySend</c> row.
@@ -2730,6 +2748,7 @@ public class ScriptRuntimeContext
/// <param name="parentExecutionId">Optional identifier of the parent execution (for routed calls).</param>
/// <param name="sourceNode">Optional cluster node identifier (node-a/node-b) for audit stamping.</param>
/// <param name="traceSink">Flow Debugger inline collector — receives the same <see cref="AuditEvent"/> <c>Send</c> hands to the writer; null when untraced.</param>
/// <param name="scriptTimeoutToken">The run's deadline; cancels the central status query (SRT-8).</param>
// Parameter ordering: executionId sits immediately after the ILogger,
// consistent with the other audit-threaded ctors. parentExecutionId is
// a trailing optional param.
@@ -2745,8 +2764,10 @@ public class ScriptRuntimeContext
IAuditWriter? auditWriter = null,
Guid? parentExecutionId = null,
string? sourceNode = null,
Action<AuditEvent>? traceSink = null)
Action<AuditEvent>? traceSink = null,
CancellationToken scriptTimeoutToken = default)
{
_scriptTimeoutToken = scriptTimeoutToken;
_storeAndForward = storeAndForward;
_siteCommunicationActor = siteCommunicationActor;
_siteId = siteId;
@@ -2789,12 +2810,13 @@ public class ScriptRuntimeContext
/// <summary>
/// Queries the delivery status of a previously-sent notification.
///
/// The query is issued to central via the site communication actor. While the
/// notification is still buffered in the site Store-and-Forward Engine — central
/// has no row for it yet (<c>Found: false</c>) but the buffer still holds the id —
/// the status is reported as the site-local <c>Forwarding</c> state. If central
/// has a row, its status is mapped through verbatim. If central does not know the
/// id and it is not buffered locally, the status is <c>Unknown</c>.
/// While the notification is still buffered in the site Store-and-Forward Engine it is
/// answered site-locally as <c>Forwarding</c> — checked FIRST (2026-12-02 review SRT-8),
/// so the common "central unreachable, still buffered" case never waits on central.
/// Otherwise the query goes to central (bounded by <see cref="CentralStatusQueryTimeout"/>
/// and the run's deadline) and a central row's status is mapped through verbatim. If central
/// does not know the id (or cannot be reached) and it is not buffered, the status is
/// <c>Unknown</c>.
/// </summary>
/// <param name="notificationId">The notification identifier returned from Send.</param>
/// <returns>The delivery status of the notification.</returns>
@@ -2804,19 +2826,24 @@ public class ScriptRuntimeContext
throw new InvalidOperationException(
"Notification status query is not available — site communication actor not wired");
// Site-local first: still in the buffer ⇒ in transit, whatever central knows.
if (await TryBufferedStatusAsync(notificationId).ConfigureAwait(false) is { } forwarding)
return forwarding;
var correlationId = Guid.NewGuid().ToString();
var query = new NotificationStatusQuery(correlationId, notificationId);
var centralTimeout = _askTimeout < CentralStatusQueryTimeout ? _askTimeout : CentralStatusQueryTimeout;
NotificationStatusResponse response;
try
{
response = await _siteCommunicationActor
.Ask<NotificationStatusResponse>(query, _askTimeout).ConfigureAwait(false);
.Ask<NotificationStatusResponse>(query, centralTimeout, _scriptTimeoutToken).ConfigureAwait(false);
}
catch (Exception ex)
catch (Exception ex) when (!_scriptTimeoutToken.IsCancellationRequested)
{
// Central could not be reached. Fall through to the buffer check: if the
// notification is still in the local S&F buffer it is Forwarding.
// Central could not be reached. Re-check the buffer: the notification may have
// been enqueued by a sweep race between the local check and here.
_logger.LogWarning(ex,
"Notification status query for {NotificationId} did not reach central",
notificationId);
@@ -2831,20 +2858,21 @@ public class ScriptRuntimeContext
response.Status, response.RetryCount, response.LastError, response.DeliveredAt);
}
// Central has no row. If the notification is still buffered at the site it
// is in transit — report the site-local Forwarding state. Otherwise it is
// genuinely unknown (never sent, or already forwarded and central lost it).
if (_storeAndForward != null)
{
var buffered = await _storeAndForward.GetMessageByIdAsync(notificationId).ConfigureAwait(false);
if (buffered != null)
{
return new NotificationDeliveryStatus(
"Forwarding", buffered.RetryCount, buffered.LastError, DeliveredAt: null);
}
}
// Central has no row. Re-check the buffer (the forwarder may have re-buffered it
// meanwhile); otherwise it is genuinely unknown (never sent, or already forwarded
// and central lost it).
return await TryBufferedStatusAsync(notificationId).ConfigureAwait(false)
?? new NotificationDeliveryStatus("Unknown", 0, null, null);
}
return new NotificationDeliveryStatus("Unknown", 0, null, null);
private async Task<NotificationDeliveryStatus?> TryBufferedStatusAsync(string notificationId)
{
if (_storeAndForward == null)
return null;
var buffered = await _storeAndForward.GetMessageByIdAsync(notificationId).ConfigureAwait(false);
return buffered == null
? null
: new NotificationDeliveryStatus("Forwarding", buffered.RetryCount, buffered.LastError, DeliveredAt: null);
}
}
@@ -916,7 +916,9 @@ public class StoreAndForwardService
// rather than burning a full timeout per remaining message.
// Skipped rows keep their RetryCount/LastAttemptAt untouched.
var outcome = await RetryMessageAsync(message);
if (outcome == RetryOutcome.TransientFailure)
if (outcome is RetryOutcome.TransientFailure
or RetryOutcome.DeliveredNotRemoved
or RetryOutcome.StorageFailure)
return;
}
}
@@ -939,8 +941,47 @@ public class StoreAndForwardService
/// short-circuit a <c>(category, target)</c> lane after its first transient
/// failure. <see cref="Skipped"/> = no attempt was made (no handler, or the
/// row's status changed under a concurrent apply); its RetryCount is untouched.
/// <see cref="DeliveredNotRemoved"/> = the handler succeeded but the buffer row could
/// not be deleted (SF-2); <see cref="StorageFailure"/> = the handler answered but the
/// resulting status write failed. Both leave the row Pending with its counters
/// untouched and stop the lane for this sweep, like a transient failure.
/// </summary>
internal enum RetryOutcome { Delivered, Parked, TransientFailure, Skipped }
internal enum RetryOutcome { Delivered, Parked, TransientFailure, Skipped, DeliveredNotRemoved, StorageFailure }
/// <summary>Attempts the post-delivery delete; how many times before giving up.</summary>
internal const int DeliveredRemoveAttempts = 3;
/// <summary>
/// Deletes a delivered message's buffer row, retrying a transient storage error (e.g.
/// <c>SQLITE_BUSY</c> on the shared LocalDb file) a few times. Returns false — after
/// logging an error — when every attempt failed; never throws.
/// </summary>
private async Task<bool> TryRemoveDeliveredMessageAsync(StoreAndForwardMessage message)
{
for (var attempt = 1; ; attempt++)
{
try
{
await _storage.RemoveMessageAsync(message.Id);
return true;
}
catch (Exception ex) when (attempt < DeliveredRemoveAttempts)
{
_logger.LogWarning(ex,
"Delivered message {MessageId} could not be removed from the buffer (attempt {Attempt}/{Max}); retrying",
message.Id, attempt, DeliveredRemoveAttempts);
await Task.Delay(TimeSpan.FromMilliseconds(50 * attempt));
}
catch (Exception ex)
{
_logger.LogError(ex,
"Message {MessageId} was DELIVERED to {Target} but could not be removed from the buffer after {Max} attempts; " +
"it stays pending and will be delivered again on the next due sweep",
message.Id, message.Target, DeliveredRemoveAttempts);
return false;
}
}
}
private async Task<RetryOutcome> RetryMessageAsync(StoreAndForwardMessage message)
{
@@ -957,19 +998,35 @@ public class StoreAndForwardService
var attemptStartUtc = DateTime.UtcNow;
var attemptStopwatch = System.Diagnostics.Stopwatch.StartNew();
// SF-2: the try covers the delivery attempt ONLY. Bookkeeping after the handler
// has answered (the row delete on success, the park on a permanent failure) is a
// storage operation, not a delivery outcome — a SQLITE_BUSY / disk-full there used
// to land in the transient catch below, which counted a retry against a call that
// had SUCCEEDED and could park it (an operator Retry then re-sent it).
bool success;
Exception? deliveryFailure = null;
try
{
var success = await handler(message);
attemptStopwatch.Stop();
if (success)
{
await _storage.RemoveMessageAsync(message.Id);
Interlocked.Decrement(ref _bufferedCount);
RaiseActivity("Delivered", message.Category,
$"Delivered to {message.Target} after {message.RetryCount} retries");
success = await handler(message);
}
catch (Exception ex)
{
success = false;
deliveryFailure = ex;
}
attemptStopwatch.Stop();
// Terminal Delivered observer notification — the audit
// bridge maps this to Attempted + CachedResolve(Delivered).
if (deliveryFailure is null && success)
{
if (!await TryRemoveDeliveredMessageAsync(message))
{
// Delivered, but the row is still Pending in the buffer, so the next due
// sweep will deliver it again (downstream idempotency is the caller's
// responsibility). RetryCount is NOT incremented and the row is NOT parked.
// The lane stops here so the rows behind it are not delivered ahead of the
// (re-)delivery of this one — per-target FIFO holds even for the duplicate.
RaiseActivity("Delivered", message.Category,
$"Delivered to {message.Target} after {message.RetryCount} retries (buffer delete failed; will re-deliver)");
await PostObserverNotification(
message,
CachedCallAttemptOutcome.Delivered,
@@ -977,15 +1034,47 @@ public class StoreAndForwardService
httpStatus: null,
occurredAtUtc: attemptStartUtc,
durationMs: (int)attemptStopwatch.ElapsedMilliseconds);
return RetryOutcome.Delivered;
return RetryOutcome.DeliveredNotRemoved;
}
Interlocked.Decrement(ref _bufferedCount);
RaiseActivity("Delivered", message.Category,
$"Delivered to {message.Target} after {message.RetryCount} retries");
// Terminal Delivered observer notification — the audit
// bridge maps this to Attempted + CachedResolve(Delivered).
await PostObserverNotification(
message,
CachedCallAttemptOutcome.Delivered,
lastError: null,
httpStatus: null,
occurredAtUtc: attemptStartUtc,
durationMs: (int)attemptStopwatch.ElapsedMilliseconds);
return RetryOutcome.Delivered;
}
if (deliveryFailure is null)
{
// Permanent failure on retry — park immediately.
message.Status = StoreAndForwardMessageStatus.Parked;
message.LastAttemptAt = DateTimeOffset.UtcNow;
message.LastError = "Permanent failure (handler returned false)";
var parked = await _storage.UpdateMessageIfStatusAsync(
message, StoreAndForwardMessageStatus.Pending);
bool parked;
try
{
parked = await _storage.UpdateMessageIfStatusAsync(
message, StoreAndForwardMessageStatus.Pending);
}
catch (Exception storageEx)
{
// A storage failure writing the park is not a delivery failure: leave the
// row Pending with its counters untouched; the next due sweep re-attempts
// it (and parks it then). Stop the lane, as for any unresolved head.
_logger.LogError(storageEx,
"Message {MessageId} to {Target} failed permanently but the park could not be written; it stays pending",
message.Id, message.Target);
return RetryOutcome.StorageFailure;
}
if (!parked)
{
_logger.LogDebug(
@@ -1008,9 +1097,10 @@ public class StoreAndForwardService
durationMs: (int)attemptStopwatch.ElapsedMilliseconds);
return RetryOutcome.Parked;
}
catch (Exception ex)
// The handler threw: a transient delivery failure.
{
attemptStopwatch.Stop();
var ex = deliveryFailure;
// Transient failure — increment retry, check max
message.RetryCount++;
message.LastAttemptAt = DateTimeOffset.UtcNow;
@@ -187,10 +187,13 @@ public class StoreAndForwardStorage
}
/// <summary>
/// Gets all messages that are due for retry (Pending status, last attempt older than retry interval).
/// Gets the messages that are due for retry (Pending status, last attempt older than retry
/// interval), restricted per <c>(category, target)</c> lane to the due rows that are not
/// preceded by an older still-pending, not-yet-due row of the same lane — a lane never
/// passes its own backing-off head (SF-1).
/// </summary>
/// <param name="limit">Maximum number of messages to return, or 0 for no limit.</param>
/// <returns>A task that resolves to the list of messages due for retry, ordered by creation time ascending.</returns>
/// <returns>A task that resolves to the eligible messages, ordered by lane rank then creation time (enqueue order within each lane).</returns>
public async Task<List<StoreAndForwardMessage>> GetMessagesForRetryAsync(int limit = 0)
{
await using var connection = OpenConnection();
@@ -199,38 +202,41 @@ public class StoreAndForwardStorage
const string cols = @"id, category, target, payload_json, retry_count, max_retries,
retry_interval_ms, created_at, last_attempt_at, status, last_error, origin_instance,
execution_id, source_script, parent_execution_id";
const string due = @"status = @pending
AND (last_attempt_at_ms IS NULL
const string dueExpr = @"(last_attempt_at_ms IS NULL
OR retry_interval_ms = 0
OR (@nowMs - last_attempt_at_ms) >= retry_interval_ms)";
if (limit > 0)
{
// Page FAIRLY across (category, target) lanes: rank each due row within its
// lane (oldest-first) and take the page by rank, so one dead target holding
// hundreds of due rows contributes one row per "round" like every other
// lane instead of owning the whole page. Within a lane rank order == created_at
// order, so per-target FIFO is preserved for the service's GroupBy.
cmd.CommandText = $@"
// Per-target FIFO (SF-1). Due-ness is decided PER LANE, not per row: the window
// runs over EVERY pending row of a (category, target) lane in enqueue order
// (created_at, rowid as the same-instant tie-break), and `blocked_by` counts the
// not-yet-due rows at or before each row. Only the lane prefix with
// blocked_by = 0 is eligible, so a younger row can never be handed out while an
// older row of the same lane is still pending but backing off — previously the
// head's failure pushed ITS last_attempt_at forward while the rows behind it
// kept their older stamps, so a later sweep delivered B before A. It also means
// a dead target is probed once per head retry interval rather than by whichever
// staggered row happened to come due on each sweep.
//
// The page is then taken FAIRLY across lanes by lane rank (review 2026-10-21
// 02/C2): one dead target holding hundreds of rows contributes one row per
// "round" like every other lane instead of owning the whole page. Within a lane
// rank order == enqueue order, preserved by the service's stable GroupBy.
cmd.CommandText = $@"
SELECT {cols}
FROM (
SELECT {cols},
ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at ASC) AS lane_rank
ROW_NUMBER() OVER lane AS lane_rank,
SUM(CASE WHEN {dueExpr} THEN 0 ELSE 1 END) OVER lane AS blocked_by
FROM sf_messages
WHERE {due}
WHERE status = @pending
WINDOW lane AS (PARTITION BY category, target ORDER BY created_at ASC, rowid ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
)
ORDER BY lane_rank ASC, created_at ASC
LIMIT @limit";
WHERE blocked_by = 0
ORDER BY lane_rank ASC, created_at ASC"
+ (limit > 0 ? "\n LIMIT @limit" : string.Empty);
if (limit > 0)
cmd.Parameters.AddWithValue("@limit", limit);
}
else
{
cmd.CommandText = $@"
SELECT {cols}
FROM sf_messages
WHERE {due}
ORDER BY created_at ASC";
}
cmd.Parameters.AddWithValue("@pending", (int)StoreAndForwardMessageStatus.Pending);
cmd.Parameters.AddWithValue("@nowMs", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());