Merge master into #937 (scenarios: keep A09 + F937)

This commit is contained in:
Joseph Doherty
2026-11-28 11:32:41 -05:00
82 changed files with 5349 additions and 210 deletions
@@ -29,11 +29,29 @@ public class ReadCommand : CommandBase
[CommandOption("max-age", Description = "Maximum cached value age in milliseconds (0 to 2147483647; default 0)")]
public double MaxAgeMilliseconds { get; init; }
/// <summary>Gets the attribute to read; <c>Value</c> (the default) is the current value.</summary>
[CommandOption("attribute", 'a', Description = "Attribute to read: Value (default), Historizing, AccessLevel, UserAccessLevel, DataType, ValueRank, ArrayDimensions, MinimumSamplingInterval, NodeClass, BrowseName, DisplayName, EventNotifier")]
public string Attribute { get; init; } = "Value";
/// <summary>The attributes <c>--attribute</c> accepts (case-insensitive), by name.</summary>
internal static readonly IReadOnlyDictionary<string, uint> AttributeIds = new Dictionary<string, uint>(StringComparer.OrdinalIgnoreCase)
{
["Value"] = Attributes.Value, ["Historizing"] = Attributes.Historizing, ["AccessLevel"] = Attributes.AccessLevel,
["UserAccessLevel"] = Attributes.UserAccessLevel, ["DataType"] = Attributes.DataType, ["ValueRank"] = Attributes.ValueRank,
["ArrayDimensions"] = Attributes.ArrayDimensions, ["MinimumSamplingInterval"] = Attributes.MinimumSamplingInterval,
["NodeClass"] = Attributes.NodeClass, ["BrowseName"] = Attributes.BrowseName, ["DisplayName"] = Attributes.DisplayName,
["EventNotifier"] = Attributes.EventNotifier,
};
/// <inheritdoc />
public override async ValueTask ExecuteAsync(IConsole console)
{
if (!double.IsFinite(MaxAgeMilliseconds) || MaxAgeMilliseconds < 0 || MaxAgeMilliseconds > int.MaxValue)
throw new CommandException("Invalid --max-age value: expected a finite number from 0 to 2147483647 milliseconds.");
if (!AttributeIds.TryGetValue(Attribute ?? "", out var attributeId))
throw new CommandException($"Invalid --attribute value: expected one of {string.Join(", ", AttributeIds.Keys)}.");
if (attributeId != Attributes.Value && MaxAgeMilliseconds != 0)
throw new CommandException("--max-age applies to the Value attribute only.");
ConfigureLogging();
@@ -56,9 +74,11 @@ public class ReadCommand : CommandBase
DataValue value;
try
{
value = MaxAgeMilliseconds == 0
? await service.ReadValueAsync(nodeId, ct)
: await service.ReadValueAsync(nodeId, TimeSpan.FromMilliseconds(MaxAgeMilliseconds), ct);
value = attributeId != Attributes.Value
? await service.ReadAttributeAsync(nodeId, attributeId, ct)
: MaxAgeMilliseconds == 0
? await service.ReadValueAsync(nodeId, ct)
: await service.ReadValueAsync(nodeId, TimeSpan.FromMilliseconds(MaxAgeMilliseconds), ct);
}
catch (ServiceResultException ex) when (ex.StatusCode != StatusCodes.BadSessionIdInvalid
&& ex.StatusCode != StatusCodes.BadConnectionClosed
@@ -68,12 +88,14 @@ public class ReadCommand : CommandBase
// BadUserAccessDenied, ...) as an exception. A read command's job is to REPORT that status,
// not crash with a stack trace — session-level failures still propagate.
await console.Output.WriteLineAsync($"Node: {NodeId}");
if (attributeId != Attributes.Value) await console.Output.WriteLineAsync($"Attribute: {Attribute}");
await console.Output.WriteLineAsync($"Value: ");
await console.Output.WriteLineAsync($"Status: {(StatusCode)ex.StatusCode} ({ex.StatusCode.SymbolicId})");
return;
}
await console.Output.WriteLineAsync($"Node: {NodeId}");
if (attributeId != Attributes.Value) await console.Output.WriteLineAsync($"Attribute: {Attribute}");
await console.Output.WriteLineAsync($"Value: {ValueFormatter.Format(ValueConverter.ToClrObject(value.WrappedValue))}");
await console.Output.WriteLineAsync($"Status: {value.StatusCode}");
await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp.ToString("O")}");
@@ -76,6 +76,14 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter
return ValidateReadResult(response.ResponseHeader, response.Results, nodeId);
}
/// <inheritdoc />
public async Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct)
{
ArrayOf<ReadValueId> nodes = [new ReadValueId { NodeId = nodeId, AttributeId = attributeId }];
var response = await _session.ReadAsync(null, 0, TimestampsToReturn.Both, nodes, ct);
return ValidateReadResult(response.ResponseHeader, response.Results, nodeId);
}
internal static DataValue ValidateReadResult(ResponseHeader? header, ArrayOf<DataValue> results, NodeId nodeId)
{
var serviceStatus = header?.ServiceResult.Code ?? StatusCodes.BadUnexpectedError;
@@ -64,6 +64,17 @@ internal interface ISessionAdapter : IDisposable
/// <summary>Reads a value using the supplied maximum cache age.</summary>
Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default);
/// <summary>
/// Reads one attribute of a node (for example <see cref="Attributes.Historizing"/>). A Bad result throws
/// <see cref="ServiceResultException"/> with its status, like <see cref="ReadValueAsync(NodeId, CancellationToken)"/>.
/// </summary>
/// <param name="nodeId">The node to read.</param>
/// <param name="attributeId">The attribute id (<see cref="Attributes"/>).</param>
/// <param name="ct">The cancellation token that aborts the read.</param>
/// <returns>The attribute's data value.</returns>
Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) =>
throw new NotSupportedException("This session adapter does not read node attributes.");
/// <summary>
/// Writes a typed value to a node on the connected OPC UA server.
/// </summary>
@@ -56,6 +56,14 @@ public interface IOpcUaClientService : IDisposable
return ReadValueAsync(nodeId, ct);
}
/// <summary>Reads one attribute of a node (for example <see cref="Attributes.Historizing"/>).</summary>
/// <param name="nodeId">The node to read.</param>
/// <param name="attributeId">The attribute id (<see cref="Attributes"/>).</param>
/// <param name="ct">The cancellation token that aborts the read.</param>
/// <returns>The attribute's data value; a Bad result throws <see cref="ServiceResultException"/>.</returns>
Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) =>
throw new NotSupportedException("This client does not read node attributes.");
/// <summary>
/// Writes an operator-supplied value to an OPC UA node after applying client-side type conversion when needed.
/// </summary>
@@ -223,6 +223,14 @@ public sealed class OpcUaClientService : IOpcUaClientService
return await _session!.ReadValueAsync(nodeId, maximumAge, ct);
}
/// <inheritdoc />
public async Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
return await _session!.ReadAttributeAsync(nodeId, attributeId, ct);
}
/// <inheritdoc />
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
{
@@ -258,8 +258,8 @@ public static class DataProtoMapper
v.Dimensions.AddRange(x.Dimensions);
if (x.ArrayElementKind is { } elementKind)
v.ArrayElementKind = (W.ValueKind)elementKind;
if (x.StableSourceId is not null)
v.StableSourceId = x.StableSourceId;
// #916: field 10 (stable_source_id) is never encoded, whatever the caller set. It carried the origin's internal
// acquisition key (driver instance id + RawPath), and no consumer needs it.
if (x.EngineeringUnits is not null)
v.EngineeringUnits = x.EngineeringUnits;
// H2: the service strips this (and the HistoryRead bit) from every response of a call that did not negotiate history.
@@ -288,7 +288,8 @@ public static class DataProtoMapper
// A2b method bits are condition grants, never node operations, so a metadata item carrying them is masked too.
(DataOperations)(x.AllowedOperations & (uint)DataOperationSets.Understood & ~(uint)DataOperationSets.ConditionGrants),
x.CatalogRevision,
x.HasStableSourceId ? x.StableSourceId : null,
// #916: dropped on decode too, so a consumer of a pre-fix origin never retains it in OriginMetadata.
null,
x.HasEngineeringUnits ? x.EngineeringUnits : null,
x.IsStale,
x.HasArrayElementKind ? (DataValueKind)x.ArrayElementKind : null,
@@ -161,6 +161,8 @@ message Metadata {
bool writable = 7;
uint32 allowed_operations = 8;
int64 catalog_revision = 9;
// DEPRECATED (#916): never sent and ignored on receipt. It carried the origin's internal acquisition key (driver
// instance id + RawPath). Kept so the field number is never reused.
optional string stable_source_id = 10;
optional string engineering_units = 11;
bool is_stale = 12;
@@ -34,6 +34,15 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// once with <see cref="AlarmInitialStateEventArgs.Unsignalable"/> set: the host then applies its
/// per-driver-type backstop timer to those conditions instead. No other shipped source should use it.
/// </para>
/// <para>
/// <b>Withdrawing (#926).</b> A source that signalled and then LOSES events for those conditions (an OPC UA
/// event-queue overflow, a publish gap) raises the event with <see cref="AlarmInitialStateEventArgs.Withdrawn"/>
/// set: the host takes "known" back from them (Uncertain on a consumer) until the source signals again or a
/// transition re-establishes one. Same ordering rule: after every alarm event raised before it. Only a source
/// that SIGNALLED withdraws: conditions that became known through the <see cref="AlarmInitialStateEventArgs.Unsignalable"/>
/// backstop are not withdrawn by a later loss (the OPC UA client has no refresh bracket there, and its loss
/// detection never re-arms the backstop) — that residual is the backstop's own.
/// </para>
/// </remarks>
public interface IAlarmInitialStateSignal
{
@@ -50,11 +59,18 @@ public sealed class AlarmInitialStateEventArgs : EventArgs
/// <see langword="true"/> when the source can never signal for these conditions (no refresh upstream);
/// the host's backstop timer applies instead of an immediate mark.
/// </param>
public AlarmInitialStateEventArgs(IReadOnlyList<string> conditionIds, bool unsignalable = false)
/// <param name="withdrawn">
/// <see langword="true"/> (#926) when the source can no longer vouch for these conditions' state (it lost events
/// after establishing them): the host withdraws "known". Exclusive with <paramref name="unsignalable"/>.
/// </param>
public AlarmInitialStateEventArgs(IReadOnlyList<string> conditionIds, bool unsignalable = false, bool withdrawn = false)
{
ArgumentNullException.ThrowIfNull(conditionIds);
if (unsignalable && withdrawn)
throw new ArgumentException("A signal is either unsignalable or a withdrawal, not both.", nameof(withdrawn));
ConditionIds = conditionIds;
Unsignalable = unsignalable;
Withdrawn = withdrawn;
}
/// <summary>The driver condition ids (= RawPaths) the completed read covers. Never "everything".</summary>
@@ -65,4 +81,10 @@ public sealed class AlarmInitialStateEventArgs : EventArgs
/// so the per-driver-type backstop timer (OpcUaClient only) decides when they become known.
/// </summary>
public bool Unsignalable { get; }
/// <summary>
/// #926: the source lost events for these conditions after establishing them, so their state is no longer
/// known. The host withdraws "known" (never starting a backstop) until the next real signal.
/// </summary>
public bool Withdrawn { get; }
}
@@ -73,6 +73,29 @@ public sealed class DataOperationPolicy
&& CredentialUsable(snapshot, caller, false);
}
/// <summary>
/// #922: would <paramref name="caller"/> be granted <paramref name="operation"/> on this mapped subject, judged on
/// everything EXCEPT the remote lease's validity? Used only to classify a refusal of a node whose lease lapsed — a caller
/// this answers false for is refused <c>BadUserAccessDenied</c> exactly as before; one it answers true for gets a retryable
/// status while the lease is renewed. It never authorizes serving anything: every served read still passes
/// <see cref="AuthorizeMapped"/> against a renewed, valid lease.
/// </summary>
public bool AuthorizeMappedSubject(DataCallerIdentity caller, OpcUaOperation operation, DataView requested,
ServingIdentity serving, MappedNamespaceSubject live, MappedSubjectResolver resolver)
{
if (resolver is null || serving is null || caller is null) return false;
var snapshot = _authority.Current;
if (!CatalogIsCurrent(resolver.LocalAuthority, snapshot)) return false;
var resolved = resolver.Resolve(requested, live);
if (resolved.Kind != MappedSubjectResolutionKind.Mapped || resolved.Subject is not { } subject
|| subject.Serving != serving || serving.CatalogEpoch <= 0 || serving.AuthorityEpoch <= 0
|| string.IsNullOrWhiteSpace(serving.NodeId) || string.IsNullOrWhiteSpace(serving.Incarnation)
|| !AllowsMappedOperation(subject, operation)) return false;
return Authorize(snapshot, caller, operation, subject.Scope, false, subject, false)
&& CatalogIsCurrent(resolver.LocalAuthority, snapshot) && ReferenceEquals(snapshot, _authority.Current)
&& CredentialUsable(snapshot, caller, false);
}
private static bool CatalogIsCurrent(IDataMappedCatalogAuthority catalog, DataPlaneAuthoritySnapshot snapshot) =>
catalog.IsActive && catalog.CatalogEpoch > 0 && catalog.AuthorityEpoch == snapshot.GenerationId
&& snapshot.HasArtifact;
@@ -169,6 +169,14 @@ public sealed class GalaxyDriver
// _alarmHandlersLock). A sentinel signals only if it is still the live one — entries delivered before a later
// subscription (or while none was live) were not delivered under it.
private GalaxyAlarmSubscriptionHandle? _streamOpenedUnder;
// lmxopcua#925: whether the feed's CURRENT stream has delivered its snapshot_complete sentinel (guarded by
// _alarmHandlersLock). A subscription that becomes live after that point gets no sentinel of its own until the
// stream reopens, so it is established by a re-read of the active-alarm set instead.
private bool _streamSnapshotDelivered;
// lmxopcua#925: the active-alarm re-read coalescer — 0 idle, 1 running, 2 running with another run requested.
private int _alarmRefreshState;
// Cancelled (and replaced) by every runtime teardown, so an in-flight re-read or its retry wait stops quietly.
private CancellationTokenSource _alarmRefreshCts = new();
// Production runtime owned by InitializeAsync (BuildProductionRuntimeAsync). The
// driver builds these when it opens a real gw session; tests bypass them by
@@ -1002,7 +1010,8 @@ public sealed class GalaxyDriver
// so they hang off the owned MxGatewayClient, not the worker session.
_alarmAcknowledger ??= new GatewayGalaxyAlarmAcknowledger(_ownedMxClient, _logger);
_alarmFeed ??= new GatewayGalaxyAlarmFeed(
_ownedMxClient.StreamAlarmsAsync, _logger, _options.MxAccess.ClientName);
_ownedMxClient.StreamAlarmsAsync, _logger, _options.MxAccess.ClientName,
queryFactory: _ownedMxClient.QueryActiveAlarmsAsync);
}
/// <summary>
@@ -1092,6 +1101,11 @@ public sealed class GalaxyDriver
}
if (releaseFeed) _alarmFeed = null;
}
// lmxopcua#925: the next feed (or the re-wired injected one) starts with no delivered stream snapshot.
lock (_alarmHandlersLock) _streamSnapshotDelivered = false;
// A re-read in flight (or waiting to retry) belongs to the torn-down runtime. Not disposed: its token may
// still be observed by the unwinding re-read.
Interlocked.Exchange(ref _alarmRefreshCts, new CancellationTokenSource()).Cancel();
if (releaseFeed)
{
try { await alarmFeed!.DisposeAsync().ConfigureAwait(false); }
@@ -2789,6 +2803,14 @@ public sealed class GalaxyDriver
}
throw;
}
// lmxopcua#925: the feed's stream is already past its sentinel (a re-subscribe on a live stream — a changed
// alarm set, or a reconnect that kept the session-less feed), so no sentinel will ever come for THIS
// subscription until the stream happens to reopen. Re-read the active-alarm set instead. A stream still in its
// snapshot phase is handled at its sentinel (OnAlarmFeedSnapshotDelivered).
bool refresh;
lock (_alarmHandlersLock) refresh = _streamSnapshotDelivered && ReferenceEquals(_alarmSubscriptions.FirstOrDefault(), handle);
if (refresh) RequestAlarmSnapshotRefresh("alarm subscription changed while the feed stream was open");
return Task.FromResult<IAlarmSubscriptionHandle>(handle);
}
@@ -3039,7 +3061,11 @@ public sealed class GalaxyDriver
/// <summary>A1 review round 2 F4: a feed stream (re)opened — record the subscription its snapshot is delivered under.</summary>
private void OnAlarmFeedStreamOpened(object? sender, EventArgs e)
{
lock (_alarmHandlersLock) _streamOpenedUnder = _alarmSubscriptions.Count > 0 ? _alarmSubscriptions[0] : null;
lock (_alarmHandlersLock)
{
_streamOpenedUnder = _alarmSubscriptions.Count > 0 ? _alarmSubscriptions[0] : null;
_streamSnapshotDelivered = false;
}
}
/// <summary>
@@ -3049,18 +3075,143 @@ public sealed class GalaxyDriver
private void OnAlarmFeedSnapshotDelivered(object? sender, EventArgs e)
{
IReadOnlyList<string> refs;
bool deliveredUnderLive;
lock (_alarmHandlersLock)
{
_streamSnapshotDelivered = true;
if (_alarmSubscriptions.Count == 0) return;
// A1 review round 2 F4: only a stream whose whole snapshot was delivered under THIS subscription.
if (!ReferenceEquals(_alarmSubscriptions[0], _streamOpenedUnder))
{
_logger.LogDebug("GalaxyDriver alarm sentinel for a stream opened under an earlier (or no) subscription — not signalled; the next stream's sentinel will.");
return;
}
refs = _alarmSubscriptionRefs;
// A1 review round 2 F4: only a stream whose whole snapshot was delivered under THIS subscription.
deliveredUnderLive = ReferenceEquals(_alarmSubscriptions[0], _streamOpenedUnder);
}
if (!deliveredUnderLive)
{
// lmxopcua#925: the subscription changed during the snapshot phase, so this sentinel cannot vouch for it and
// no later sentinel comes until the stream reopens — re-read the active-alarm set instead (when the gateway
// client supports it; otherwise the next stream's sentinel signals, and F5 diagnoses the wait).
_logger.LogDebug("GalaxyDriver alarm sentinel for a stream opened under an earlier (or no) subscription — not signalled; re-reading the active-alarm set.");
RequestAlarmSnapshotRefresh("alarm subscription changed during the feed's snapshot phase");
return;
}
if (refs.Count == 0) return;
try
{
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs));
}
catch (Exception ex)
{
_logger.LogWarning(ex, "GalaxyDriver InitialAlarmStateDelivered handler threw — continuing.");
}
}
/// <summary>Delay between attempts of a failed active-alarm re-read (lmxopcua#925) — tests shorten it.</summary>
internal TimeSpan AlarmSnapshotRefreshRetryDelay { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>Attempts per active-alarm re-read before it gives up (the next stream sentinel or F5 then takes over).</summary>
internal const int AlarmSnapshotRefreshAttempts = 3;
private static readonly TimeSpan AlarmSnapshotRefreshTimeout = TimeSpan.FromSeconds(30);
/// <summary>
/// lmxopcua#925: schedule a re-read of the gateway's active-alarm set that, once replayed, signals the live
/// subscription's refs as delivered — the gap-free replacement for a <c>snapshot_complete</c> sentinel the
/// open stream will not send again. Coalesced: at most one re-read runs, and requests made while it runs
/// collapse into ONE follow-up run. A no-op when the feed has no query (test fakes, or a feed built without one).
/// </summary>
private void RequestAlarmSnapshotRefresh(string reason)
{
IGalaxyAlarmFeed? feed;
lock (_alarmFeedLock) feed = _alarmFeedWired ? _alarmFeed : null;
if (feed is null || !feed.SupportsSnapshotRefresh || _disposed) return;
while (true)
{
switch (Volatile.Read(ref _alarmRefreshState))
{
case 0:
if (Interlocked.CompareExchange(ref _alarmRefreshState, 1, 0) != 0) continue;
_logger.LogDebug("GalaxyDriver re-reading the active-alarm set: {Reason}", reason);
_ = Task.Run(RunAlarmSnapshotRefreshesAsync);
return;
case 1:
if (Interlocked.CompareExchange(ref _alarmRefreshState, 2, 1) != 1) continue;
return;
default:
return; // a follow-up run is already queued
}
}
}
private async Task RunAlarmSnapshotRefreshesAsync()
{
while (true)
{
try
{
await RefreshAlarmSnapshotOnceAsync(Volatile.Read(ref _alarmRefreshCts).Token).ConfigureAwait(false);
}
catch (Exception ex)
{
// Logged, then the coalescing step below still runs: a follow-up requested meanwhile is not lost.
_logger.LogWarning(ex, "GalaxyDriver active-alarm re-read failed unexpectedly");
}
// 1 → 0: nothing was requested meanwhile. 2: run once more for the requests that arrived.
if (Interlocked.CompareExchange(ref _alarmRefreshState, 0, 1) == 1) return;
Volatile.Write(ref _alarmRefreshState, 1);
}
}
private async Task RefreshAlarmSnapshotOnceAsync(CancellationToken teardown)
{
GalaxyAlarmSubscriptionHandle? under;
IGalaxyAlarmFeed? feed;
lock (_alarmFeedLock) feed = _alarmFeedWired ? _alarmFeed : null;
lock (_alarmHandlersLock) under = _alarmSubscriptions.Count > 0 ? _alarmSubscriptions[0] : null;
if (feed is null || under is null) return;
for (var attempt = 1; ; attempt++)
{
if (_disposed || teardown.IsCancellationRequested) return;
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(teardown);
timeout.CancelAfter(AlarmSnapshotRefreshTimeout);
if (!await feed.RefreshSnapshotAsync(timeout.Token).ConfigureAwait(false)) return;
break;
}
catch (Exception ex) when (ex is ObjectDisposedException || _disposed || teardown.IsCancellationRequested)
{
return; // the feed or the driver is being torn down
}
catch (Grpc.Core.RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.Unimplemented)
{
_logger.LogWarning("GalaxyDriver: the gateway does not implement QueryActiveAlarms — alarm conditions of a changed subscription stay unestablished until the feed stream reopens");
return;
}
catch (Exception ex) when (attempt < AlarmSnapshotRefreshAttempts)
{
_logger.LogWarning("GalaxyDriver active-alarm re-read attempt {Attempt} failed ({Reason}); retrying in {Delay}",
attempt, ex.Message, AlarmSnapshotRefreshRetryDelay);
try { await Task.Delay(AlarmSnapshotRefreshRetryDelay, teardown).ConfigureAwait(false); }
catch (OperationCanceledException) { return; } // torn down while waiting to retry
}
catch (Exception ex)
{
_logger.LogWarning(ex, "GalaxyDriver active-alarm re-read failed after {Attempts} attempts — the subscription's alarm conditions stay unestablished until the feed stream reopens", attempt);
return;
}
}
// Signal only for the subscription the re-read was made under, through the feed that made it: a subscription
// that replaced it requested its own (coalesced) run; a torn-down feed's replay was never bridged.
IReadOnlyList<string> refs;
lock (_alarmFeedLock) if (!_alarmFeedWired || !ReferenceEquals(_alarmFeed, feed)) return;
lock (_alarmHandlersLock)
{
if (_alarmSubscriptions.Count == 0 || !ReferenceEquals(_alarmSubscriptions[0], under)) return;
refs = _alarmSubscriptionRefs;
}
if (refs.Count == 0) return;
try
{
@@ -43,6 +43,16 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
internal delegate IAsyncEnumerable<AlarmFeedMessage> AlarmStreamFactory(
StreamAlarmsRequest request, CancellationToken cancellationToken);
/// <summary>
/// Reads the gateway's current active-alarm set (lmxopcua#925). Matches the method group
/// <c>MxGatewayClient.QueryActiveAlarmsAsync</c>.
/// </summary>
/// <param name="request">The query request parameters.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The async stream of active-alarm snapshots.</returns>
internal delegate IAsyncEnumerable<ActiveAlarmSnapshot> ActiveAlarmQueryFactory(
QueryActiveAlarmsRequest request, CancellationToken cancellationToken);
private static readonly TimeSpan DefaultReconnectDelay = TimeSpan.FromSeconds(5);
// Shares the driver meter name so a host-level MeterListener catches feed counters
@@ -54,11 +64,35 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
private static readonly Counter<long> AlarmTransitionsDecodingFailures =
Meter.CreateCounter<long>("galaxy.alarm_feed.transitions.decoding_failures", unit: "{event}",
description: "Alarm feed messages dropped for a missing body or unspecified transition kind.");
private static readonly Counter<long> AlarmSnapshotRefreshes =
Meter.CreateCounter<long>("galaxy.alarm_feed.snapshot_refreshes", unit: "{refresh}",
description: "Active-alarm set re-reads (QueryActiveAlarms) completed while the alarm stream stayed open (lmxopcua#925).");
private static readonly Counter<long> AlarmSnapshotRefreshEntriesSuperseded =
Meter.CreateCounter<long>("galaxy.alarm_feed.snapshot_refresh.superseded", unit: "{entry}",
description: "Re-read entries not replayed because the live stream delivered a newer message for the same alarm.");
private static readonly Counter<long> AlarmFeedReconnects =
Meter.CreateCounter<long>("galaxy.alarm_feed.reconnects", unit: "{reconnect}",
description: "Times the alarm feed re-opened its StreamAlarms stream after a transport fault.");
private readonly AlarmStreamFactory _streamFactory;
private readonly ActiveAlarmQueryFactory? _queryFactory;
// lmxopcua#925: serialises live dispatch with a re-read's replay, so "did the live stream already deliver a newer
// message for this alarm" and the replay of the re-read entry are one atomic step.
private readonly Lock _dispatchLock = new();
// The alarms the live stream delivered a message for since the in-flight re-read was issued (null when none is in
// flight), mapped to whether any of them carried the FULL state (snapshot entry, Raise, Retrigger, Clear) — true —
// or only the ack dimension (Acknowledge) — false. Guarded by _dispatchLock.
private Dictionary<string, bool>? _touchedDuringRefresh;
// Review r1 #2: bumped (under _dispatchLock) each time a stream is (re)opened, before any of its messages. A
// re-read replays only if no stream opened since it was issued: an alarm that cleared in a reopen gap is merely
// ABSENT from the new snapshot, so the touched map cannot catch the re-read's stale entry for it.
private long _streamEpoch;
// Whether the current stream has delivered its snapshot_complete sentinel. Guarded by _dispatchLock. A re-read is
// pointless (and could signal mid-snapshot) while it has not: that stream's own sentinel covers the subscription.
private bool _streamSnapshotComplete;
// One re-read at a time (a second one waits for the first).
private readonly SemaphoreSlim _refreshGate = new(1, 1);
private readonly ILogger _logger;
private readonly string _alarmFilterPrefix;
private readonly TimeSpan _reconnectDelay;
@@ -86,14 +120,20 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
/// <param name="clientName">An optional client name for tagging log entries.</param>
/// <param name="alarmFilterPrefix">An optional prefix to filter alarms in the stream.</param>
/// <param name="reconnectDelay">An optional delay before reconnecting after a stream fault.</param>
/// <param name="queryFactory">
/// An optional factory over the gateway's <c>QueryActiveAlarms</c> RPC; when given, <see cref="RefreshSnapshotAsync"/>
/// re-reads the active-alarm set without reopening the stream (lmxopcua#925).
/// </param>
public GatewayGalaxyAlarmFeed(
AlarmStreamFactory streamFactory,
ILogger? logger = null,
string? clientName = null,
string? alarmFilterPrefix = null,
TimeSpan? reconnectDelay = null)
TimeSpan? reconnectDelay = null,
ActiveAlarmQueryFactory? queryFactory = null)
{
_streamFactory = streamFactory ?? throw new ArgumentNullException(nameof(streamFactory));
_queryFactory = queryFactory;
_logger = logger ?? NullLogger.Instance;
_alarmFilterPrefix = alarmFilterPrefix ?? string.Empty;
_reconnectDelay = reconnectDelay ?? DefaultReconnectDelay;
@@ -130,6 +170,12 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
AlarmFilterPrefix = _alarmFilterPrefix,
};
lock (_dispatchLock)
{
_streamEpoch++;
_streamSnapshotComplete = false;
}
// A1 review round 2 F4: before any message of this stream, on this (the dispatch) thread.
try { StreamOpened?.Invoke(this, EventArgs.Empty); }
catch (Exception ex) { _logger.LogWarning(ex, "Galaxy alarm feed StreamOpened handler threw — continuing."); }
@@ -163,19 +209,134 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
}
}
/// <inheritdoc />
public bool SupportsSnapshotRefresh => _queryFactory is not null;
/// <inheritdoc />
public async Task<bool> RefreshSnapshotAsync(CancellationToken cancellationToken)
{
if (_queryFactory is null || _disposed) return false;
CancellationTokenSource linked;
try { linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token); }
catch (ObjectDisposedException) { return false; } // disposed concurrently: not an RPC failure
using var _ = linked;
await _refreshGate.WaitAsync(linked.Token).ConfigureAwait(false);
try
{
// Track BEFORE the query is issued: any live message dispatched from here on may be newer than the
// query's view of that alarm.
var touched = new Dictionary<string, bool>(StringComparer.Ordinal);
long epoch;
lock (_dispatchLock)
{
if (!_streamSnapshotComplete) return false; // the current stream's own sentinel covers it
epoch = _streamEpoch;
_touchedDuringRefresh = touched;
}
try
{
var entries = new List<ActiveAlarmSnapshot>();
var request = new QueryActiveAlarmsRequest
{
ClientCorrelationId = Guid.NewGuid().ToString("N"),
AlarmFilterPrefix = _alarmFilterPrefix,
};
await foreach (var entry in _queryFactory(request, linked.Token)
.WithCancellation(linked.Token).ConfigureAwait(false))
{
entries.Add(entry);
}
var superseded = 0;
lock (_dispatchLock)
{
linked.Token.ThrowIfCancellationRequested();
if (_streamEpoch != epoch)
{
// Review r1 #2: a stream (re)opened meanwhile. Its snapshot (and sentinel) is the newer
// statement of every alarm; replaying this older view could resurrect one that cleared in the gap.
_logger.LogDebug("Galaxy alarm feed re-read discarded: the stream reopened while it was in flight.");
return false;
}
foreach (var entry in entries)
{
if (!touched.TryGetValue(entry.AlarmFullReference, out var fullState))
{
DispatchSnapshotEntry(entry);
}
else if (fullState)
{
superseded++; // a newer full statement of this alarm already reached the host
}
else
{
// Review r1 #1: only acknowledged since the query read it — the entry's ACTIVE state still
// stands, merged with the ack (Active ⇒ ActiveAcked; ActiveAcked / Inactive unchanged).
DispatchSnapshotEntry(entry.CurrentState == AlarmConditionState.Active
? MergeAcknowledged(entry)
: entry);
}
}
}
AlarmSnapshotRefreshes.Add(1, _clientTag);
if (superseded > 0) AlarmSnapshotRefreshEntriesSuperseded.Add(superseded, _clientTag);
_logger.LogDebug(
"Galaxy alarm feed re-read the active-alarm set: {Count} entr(ies) replayed, {Superseded} superseded by the live stream.",
entries.Count - superseded, superseded);
return true;
}
finally
{
lock (_dispatchLock) _touchedDuringRefresh = null;
}
}
finally
{
_refreshGate.Release();
}
}
private static ActiveAlarmSnapshot MergeAcknowledged(ActiveAlarmSnapshot entry)
{
var merged = entry.Clone();
merged.CurrentState = AlarmConditionState.ActiveAcked;
return merged;
}
/// <summary>Under <see cref="_dispatchLock"/>: note a live message for an alarm while a re-read is in flight.</summary>
private void NoteTouched(string reference, bool fullState)
{
if (_touchedDuringRefresh is not { } touched) return;
touched[reference] = fullState || (touched.TryGetValue(reference, out var prior) && prior);
}
private void Dispatch(AlarmFeedMessage message)
{
lock (_dispatchLock)
{
DispatchLocked(message);
}
}
private void DispatchLocked(AlarmFeedMessage message)
{
switch (message.PayloadCase)
{
case AlarmFeedMessage.PayloadOneofCase.ActiveAlarm:
NoteTouched(message.ActiveAlarm.AlarmFullReference, fullState: true);
DispatchSnapshotEntry(message.ActiveAlarm);
break;
case AlarmFeedMessage.PayloadOneofCase.Transition:
// An Acknowledge carries only the ack dimension; every other kind restates the active state too.
NoteTouched(message.Transition.AlarmFullReference,
fullState: message.Transition.TransitionKind != AlarmTransitionKind.Acknowledge);
DispatchTransition(message.Transition);
break;
case AlarmFeedMessage.PayloadOneofCase.SnapshotComplete:
_logger.LogDebug("Galaxy alarm feed active-alarm snapshot complete.");
_initialSnapshot.TrySetResult();
_streamSnapshotComplete = true; // before the signal, whose handler may request a re-read
// grpc-data A1: the ordered per-sentinel signal — on THIS thread, after the snapshot entries above
// were raised; every reopened stream's sentinel raises it again.
RaiseSnapshotDelivered();
@@ -318,5 +479,6 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
try { await _loop.ConfigureAwait(false); } catch { /* shutdown */ }
}
_cts.Dispose();
// _refreshGate is deliberately not disposed: a re-read unwinding from the cancellation above still releases it.
}
}
@@ -53,4 +53,26 @@ internal interface IGalaxyAlarmFeed : IAsyncDisposable
/// sentinel signals only if that subscription is still the live one. The default accessors make it a no-op.
/// </summary>
event EventHandler? StreamOpened { add { } remove { } }
/// <summary>
/// True when <see cref="RefreshSnapshotAsync"/> can re-read the gateway's active-alarm set without reopening
/// the stream (lmxopcua#925). The default is false, for feeds with no query (the test fakes).
/// </summary>
bool SupportsSnapshotRefresh => false;
/// <summary>
/// lmxopcua#925: re-read the gateway's current active-alarm set (<c>QueryActiveAlarms</c>, the same monitor
/// cache the stream's opening snapshot comes from) and raise each entry on <see cref="OnAlarmTransition"/> as a
/// restatement, exactly like a snapshot entry, while the live stream stays open. An entry is skipped when the
/// live stream delivered a full-state message (snapshot entry, Raise, Retrigger, Clear) for the same alarm after
/// the query was issued: that message is at least as new as the query's view, and replaying the older view after
/// it would be a phantom transition. An Acknowledge alone is merged instead (an Active entry replays as
/// ActiveAcked). Completes true once every entry was raised; false — nothing replayed — when the feed has no
/// query, is disposed, the current stream has not delivered its sentinel yet, or a stream (re)opened while the
/// query was in flight (that stream's own sentinel then covers the subscription). Throws on an RPC failure.
/// Raises no signal itself — the caller decides which subscription the re-read establishes.
/// </summary>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>True when the set was re-read and its entries raised.</returns>
Task<bool> RefreshSnapshotAsync(CancellationToken cancellationToken) => Task.FromResult(false);
}
@@ -26,6 +26,10 @@ internal sealed class OpcUaClientDiagnostics
public const string KeepAliveRecovered = "keepalive_recovered";
/// <summary>A late replayed notification (source time at or below the ref's high-water mark) was dropped inside the post-recovery replay window.</summary>
public const string StaleNotificationDropped = "stale_notification_dropped";
/// <summary>#926: the upstream reported an <c>EventQueueOverflowEventType</c> on an alarm event item (events lost).</summary>
public const string AlarmEventQueueOverflow = "alarm_event_queue_overflow";
/// <summary>#926: a RefreshEnd was NOT taken as "initial alarm state delivered" because its replay was lossy.</summary>
public const string AlarmRefreshLossy = "alarm_refresh_lossy";
private readonly string _driverInstanceId;
@@ -268,6 +268,15 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
ReportRefreshUnsignalable(ras.Subscription);
}
/// <summary>Test-only seam (#926): a ConditionRefresh call of <paramref name="handle"/>'s subscription failed, as the
/// refresh catch reports it.</summary>
/// <param name="handle">The alarm subscription handle.</param>
internal void ReportRefreshFailedForTest(IAlarmSubscriptionHandle handle)
{
if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras))
NoteConditionRefreshFailed(ras.Subscription);
}
/// <summary>
/// Test-only seam to install the <see cref="NamespaceMap"/> that connect builds at
/// runtime, so the v3 RawPath → upstream node id resolution can be exercised without a live
@@ -1365,7 +1374,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
foreach (var key in _alarmSubscriptions.Keys)
{
if (!_alarmSubscriptions.TryRemove(key, out var ras)) continue;
RemoteAlarmSubscription? ras;
// #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it.
lock (_alarmStateLock)
if (!_alarmSubscriptions.TryRemove(key, out ras)) continue;
try { ras.EventItem.Notification -= ras.Handler; }
catch { /* best-effort */ }
if (sessionAlive) deletes.Add(DeleteSubscriptionBestEffortAsync(ras.Subscription, budget.Token));
@@ -2434,6 +2446,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private const int AlarmFieldAckedState = 8;
private const int AlarmFieldBranchId = 9;
/// <summary>#926: the requested queue size of the alarm event item (was 1000). See its use.</summary>
internal const uint AlarmEventQueueSize = 10_000;
/// <summary>#926 test seam (the live overflow gate shrinks it): the queue size the alarm event item requests.</summary>
internal uint AlarmEventItemQueueSize { get; set; } = AlarmEventQueueSize;
/// <summary>#926 test seam (the live gate flips it to make a lossy replay KEEP its RefreshEnd): the alarm event
/// item's DiscardOldest. Production: false (the newest events are dropped on overflow).</summary>
internal bool AlarmEventItemDiscardOldest { get; set; }
/// <inheritdoc />
public async Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(
IReadOnlyList<string> sourceNodeIds, CancellationToken cancellationToken)
@@ -2574,8 +2596,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
StartNodeId = ObjectIds.Server,
AttributeId = Attributes.EventNotifier,
MonitoringMode = MonitoringMode.Reporting,
QueueSize = 1000, // deep queue — a server can fire many alarms in bursts
DiscardOldest = false,
// #926: deep queue — a ConditionRefresh replays EVERY retained upstream condition in one burst, and a
// server can fire many alarms at once. An overflow is still detected (EventQueueOverflowEventType ⇒ the
// refresh's RefreshEnd does not signal and it is re-run); the depth only makes it rarer. The server
// may revise it down (logged with the retry budget's exhaustion).
QueueSize = AlarmEventItemQueueSize,
DiscardOldest = AlarmEventItemDiscardOldest,
Filter = filter,
})
{
@@ -2623,7 +2649,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
public async Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken)
{
if (handle is not OpcUaAlarmSubscriptionHandle h) return;
if (!_alarmSubscriptions.TryRemove(h.Id, out var rs)) return;
RemoteAlarmSubscription? rs;
// #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it.
lock (_alarmStateLock)
if (!_alarmSubscriptions.TryRemove(h.Id, out rs)) return;
var emptied = NoteSubscriptionDeleted();
await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false);
@@ -2790,6 +2819,21 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// without this it would feed RouteAlarmEvent alongside the real one.
if (!_alarmSubscriptions.ContainsKey(handle.Id)) return;
RecordLivenessEvidence();
RouteAlarmEventFieldList(efl, sourceFilter, handle);
}
/// <summary>
/// Route one delivered event: first #926's publish-sequence check (a gap inside a refresh bracket makes it
/// lossy — checked BEFORE the event, so a RefreshEnd in the first message after the gap is already suppressed),
/// then <see cref="RouteAlarmEvent"/>.
/// </summary>
/// <param name="efl">The delivered event (the SDK sets <c>Message</c> to its notification message).</param>
/// <param name="sourceFilter">The subscription's upstream-key → RawPath index.</param>
/// <param name="handle">The subscription handle.</param>
internal void RouteAlarmEventFieldList(
EventFieldList efl, IReadOnlyDictionary<string, string> sourceFilter, IAlarmSubscriptionHandle handle)
{
NoteAlarmMessageSequence(handle, efl.Message?.SequenceNumber ?? 0);
RouteAlarmEvent(efl.EventFields.ToList(), sourceFilter, handle);
}
@@ -2826,25 +2870,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
internal void RouteAlarmEvent(
IReadOnlyList<Variant> fields, IReadOnlyDictionary<string, string> sourceFilter, IAlarmSubscriptionHandle handle)
{
if (IsRefreshRequired(fields))
if (fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId markerType
&& IsBracketEventType(markerType))
{
// Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh.
// r2 R2-1: bound to the session's work token, which a shutdown cancels first thing.
var sessionWork = _sessionWorkCts.Token;
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork));
return;
}
if (IsRefreshEnd(fields))
{
// grpc-data A1 (F1): the refresh replay this subscription requested is complete and every refreshed event
// before it was routed (sequential publishing, G2). Under the emission lock, so the signal is ordered
// behind every emission. Covers the subscription's alarm RawPaths.
lock (_alarmStateLock)
{
if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras))
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false);
}
RouteBracketEvent(markerType, handle);
return;
}
@@ -2893,6 +2922,346 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <param name="Severity">Exact severity last told (null before any event).</param>
private readonly record struct AlarmToldState(bool Active, bool Acked, string? Message, int? Severity);
/// <summary>#926: the event types that drive the refresh bracket (never alarms): the three ConditionRefresh
/// markers and the server's <c>EventQueueOverflowEventType</c>.</summary>
/// <param name="t">The event's EventType.</param>
/// <returns>Whether it is a bracket event.</returns>
private static bool IsBracketEventType(NodeId t) =>
t == ObjectTypeIds.RefreshStartEventType || t == ObjectTypeIds.RefreshEndEventType
|| t == ObjectTypeIds.RefreshRequiredEventType || t == ObjectTypeIds.EventQueueOverflowEventType;
/// <summary>
/// #926 — route one bracket event. Matched by EventType BEFORE any source filtering: an
/// <c>EventQueueOverflowEventType</c> (Part 4) and the refresh markers come from the Server object, never
/// from an authored condition source, so the projector's source filter would drop them.
/// <list type="bullet">
/// <item>RefreshStart opens a bracket and clears the loss record — unless a bracket is still open (its
/// RefreshEnd never arrived): an overlapping start is itself a loss, kept.</item>
/// <item>EventQueueOverflow is a definite loss: the bracket's RefreshEnd will not signal, and a bounded driver
/// re-refresh is requested (also outside a bracket — a lost live transition is repaired by a replay).</item>
/// <item>RefreshRequired is a loss too; it keeps its existing (coalesced) sweep, which IS the re-refresh.</item>
/// <item>RefreshEnd signals (grpc-data A1) only for a bracket that was opened and saw no loss; otherwise it
/// stays silent — the conditions stay unknown (Uncertain), the safe invariant — and requests the
/// re-refresh if none was yet.</item>
/// </list>
/// Any loss after the subscription signalled also WITHDRAWS "known" from its conditions (see
/// <see cref="NoteBracketLoss"/>).
/// </summary>
/// <param name="type">The bracket event's EventType.</param>
/// <param name="handle">The subscription the event arrived on.</param>
private void RouteBracketEvent(NodeId type, IAlarmSubscriptionHandle handle)
{
RemoteAlarmSubscription? ras = null;
if (handle is OpcUaAlarmSubscriptionHandle h) _alarmSubscriptions.TryGetValue(h.Id, out ras);
if (type == ObjectTypeIds.RefreshRequiredEventType)
{
if (ras is not null)
lock (_alarmStateLock)
{
// The sweep below re-refreshes this subscription, so no driver retry is requested for it.
NoteBracketLoss(ras, "RefreshRequired", requestRetry: false);
ras.Bracket.RetryRequestedSinceStart = true;
}
RequestRefreshRequiredSweep();
return;
}
if (ras is null) return; // a released / stray subscription: no bracket, no signal (G5)
lock (_alarmStateLock)
{
var b = ras.Bracket;
if (type == ObjectTypeIds.RefreshStartEventType)
{
if (b.Open)
{
// The previous bracket's RefreshEnd never arrived (or brackets overlap): that is a loss, and it must
// not be erased by this start.
NoteBracketLoss(ras, "overlapping RefreshStart (the previous RefreshEnd never arrived)", requestRetry: false);
}
else
{
b.LossSinceStart = null;
b.RetryRequestedSinceStart = false;
}
b.Open = true;
}
else if (type == ObjectTypeIds.EventQueueOverflowEventType)
{
_diag.Record(OpcUaClientDiagnostics.AlarmEventQueueOverflow);
NoteBracketLoss(ras, "EventQueueOverflow (the upstream discarded events of this subscription)",
requestRetry: true);
}
else if (type == ObjectTypeIds.RefreshEndEventType)
{
var opened = b.Open;
b.Open = false;
if (opened && b.LossSinceStart is null)
{
// #926 review r2: re-checked UNDER the lock (the lookup above ran outside it, and an unsubscribe
// removes the record under this lock): a released subscription never signals.
if (!IsRegisteredLocked(ras)) return;
// grpc-data A1 (F1): the refresh replay this subscription requested is complete, lossless, and every
// refreshed event before it was routed (sequential publishing, G2). Under the emission lock, so the
// signal is ordered behind every emission. Covers the subscription's alarm RawPaths. Ends the
// lossy episode: the next loss gets a fresh budget.
b.Retries = 0;
b.ExhaustedLogged = false;
b.Signalled = true;
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false);
return;
}
var reason = b.LossSinceStart ?? "RefreshEnd without its RefreshStart (the bracket start was lost)";
_diag.Record(OpcUaClientDiagnostics.AlarmRefreshLossy);
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': RefreshEnd on alarm subscription {SubscriptionId} NOT taken " +
"as 'initial alarm state delivered' — {Reason}; its conditions stay unknown until a lossless refresh.",
_driverInstanceId, ras.Handle.DiagnosticId, reason);
WithdrawKnownLocked(ras, reason);
if (!b.RetryRequestedSinceStart)
b.RetryRequestedSinceStart = ScheduleAlarmRefreshRetryLocked(ras, reason);
}
}
}
/// <summary>
/// #926: record a loss against <paramref name="ras"/>'s bracket, withdraw "known" if the subscription had
/// signalled (an event lost AFTER the conditions were declared known — a live Raise in an overflowed queue or a
/// skipped publish message — would otherwise leave a consumer holding a known-inactive condition that is active
/// upstream), and (once per bracket) request a bounded re-refresh. Caller holds <c>_alarmStateLock</c>.
/// </summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="reason">What was lost (logged).</param>
/// <param name="requestRetry">Whether the driver itself should re-run ConditionRefresh.</param>
private void NoteBracketLoss(RemoteAlarmSubscription ras, string reason, bool requestRetry)
{
var b = ras.Bracket;
b.LossSinceStart ??= reason;
WithdrawKnownLocked(ras, reason);
if (!requestRetry || b.RetryRequestedSinceStart) return;
// Only a retry actually scheduled (or already pending) covers this bracket's loss; a spent budget leaves the
// request open, so a loss after the cool-down can still start one.
b.RetryRequestedSinceStart = ScheduleAlarmRefreshRetryLocked(ras, reason);
}
/// <summary>#926: if <paramref name="ras"/> signalled since its last loss, tell the host its conditions are no longer
/// known (<see cref="AlarmInitialStateEventArgs.Withdrawn"/>) — ordered after every alarm event already raised, as the
/// signal is. A later clean RefreshEnd signals them known again. Caller holds <c>_alarmStateLock</c>.</summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="reason">Why (logged).</param>
private void WithdrawKnownLocked(RemoteAlarmSubscription ras, string reason)
{
if (!ras.Bracket.Signalled) return;
ras.Bracket.Signalled = false;
// #926 review r2: a stale record (unsubscribed after the caller's lookup, still Signalled) must not withdraw
// refs that may now belong to a NEW subscription. Checked under the lock the unsubscribe removes it under.
if (!IsRegisteredLocked(ras)) return;
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost events after its conditions " +
"were declared known ({Reason}); withdrawing 'known' until a lossless ConditionRefresh.",
_driverInstanceId, ras.Handle.DiagnosticId, reason);
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false, withdrawn: true);
}
/// <summary>#926 review r2: <paramref name="ras"/> is still the registered subscription for its handle. Caller holds
/// <c>_alarmStateLock</c>; removals take it too, so the answer holds for the rest of the critical section.</summary>
/// <param name="ras">The alarm subscription record.</param>
/// <returns>Whether it is the live registration.</returns>
private bool IsRegisteredLocked(RemoteAlarmSubscription ras) =>
_alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) && ReferenceEquals(current, ras);
/// <summary>
/// #926: the publish-sequence check of alarm subscription <paramref name="handle"/>. The alarm subscription holds
/// exactly one (event) monitored item, so every data-bearing notification message it receives carries its
/// events and consumes one sequence number (keep-alives consume none). With <c>SequentialPublishing</c> the SDK
/// delivers messages in order and waits for a missing one (republish); if the republish fails it SKIPS the gap
/// and delivers the next message. That skip is reported to nothing the driver can observe — SDK 2.0.1 raises its
/// <c>PublishStateChangedMask.Republish</c> only in a message-worker pass that also delivers a message, which a
/// gap holding every later message prevents (pinned by the real-SDK test). So the driver compares sequence
/// numbers itself: a newer message that is not the successor of the previous one means messages were lost —
/// inside a bracket the replay is lossy, outside it a live transition may be lost; either way it is a loss
/// (withdraw if signalled + bounded re-refresh). An OLDER (or repeated) number is ignored and not recorded, so a
/// stray late message cannot make the next in-order one read as a second gap. A StatusChange-only message
/// (transfer / timeout) also consumes a number and reads as a gap: a bounded extra refresh, never a wrong signal.
/// </summary>
/// <param name="handle">The alarm subscription handle.</param>
/// <param name="sequenceNumber">The delivered message's sequence number (0 = unknown, ignored).</param>
internal void NoteAlarmMessageSequence(IAlarmSubscriptionHandle handle, uint sequenceNumber)
{
if (sequenceNumber == 0) return;
if (handle is not OpcUaAlarmSubscriptionHandle h || !_alarmSubscriptions.TryGetValue(h.Id, out var ras)) return;
lock (_alarmStateLock)
{
var b = ras.Bracket;
var last = b.LastSequenceNumber;
if (last == 0) { b.LastSequenceNumber = sequenceNumber; return; }
// Wrap-aware "newer" (RFC 1982-style, as the SDK compares): forward distance in (0, 2^31). Sequence numbers
// skip 0 on the wrap (… uint.MaxValue, 1 …), so the successor of uint.MaxValue is 1.
var forward = unchecked(sequenceNumber - last);
if (forward == 0 || forward >= 0x8000_0000u) return; // repeat or older: ignore, do not record
b.LastSequenceNumber = sequenceNumber;
var next = last == uint.MaxValue ? 1u : last + 1;
if (sequenceNumber == next) return;
NoteBracketLoss(ras,
$"publish message(s) lost (sequence {last} → {sequenceNumber}){(b.Open ? " during a refresh replay" : "")}",
requestRetry: true);
}
}
/// <summary>#926: the bounded number of driver-initiated re-refreshes per lossy episode (an episode ends with a clean
/// RefreshEnd). When spent, the conditions stay unknown (Uncertain) and the host's
/// <c>ConditionKnownSignalTimeout</c> diagnostic reports them — never known-inactive. After
/// <see cref="AlarmRefreshRetryCooldown"/> without a retry, a further loss starts a new budget, so a structurally
/// lossy upstream is retried at most <see cref="MaxAlarmRefreshRetries"/> times per cool-down — no storm, and no
/// permanent give-up either.</summary>
internal const int MaxAlarmRefreshRetries = 3;
/// <summary>#926: the first re-refresh delay; each further retry doubles it (2 s, 4 s, 8 s), giving the
/// upstream time to drain whatever overflowed. Test seam.</summary>
internal TimeSpan AlarmRefreshRetryBaseDelay { get; set; } = TimeSpan.FromSeconds(2);
/// <summary>#926: after the budget is spent, how long since the last retry before a new loss gets a new budget.
/// Test seam.</summary>
internal TimeSpan AlarmRefreshRetryCooldown { get; set; } = TimeSpan.FromMinutes(5);
/// <summary>#926 test seam: replaces the ConditionRefresh call of a driver re-refresh.</summary>
internal Func<Subscription, CancellationToken, Task>? AlarmRefreshRetryInvokerForTest { get; set; }
/// <summary>#926: schedule one bounded re-refresh of <paramref name="ras"/> (coalesced while one is pending).
/// Caller holds <c>_alarmStateLock</c>.</summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="reason">Why (logged).</param>
/// <returns>Whether a retry is now pending (scheduled here or already) — false when the budget is spent.</returns>
private bool ScheduleAlarmRefreshRetryLocked(RemoteAlarmSubscription ras, string reason)
{
var b = ras.Bracket;
if (b.RetryPending) return true;
var now = Clock.GetUtcNow().UtcDateTime;
if (b.Retries >= MaxAlarmRefreshRetries && b.LastRetryUtc is { } lastRetry && now - lastRetry >= AlarmRefreshRetryCooldown)
{
b.Retries = 0; // a new episode after the cool-down
b.ExhaustedLogged = false;
}
if (b.Retries >= MaxAlarmRefreshRetries)
{
if (!b.ExhaustedLogged)
{
b.ExhaustedLogged = true;
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost refresh events " +
"{Retries} time(s) in a row ({Reason}); no further re-refresh for {Cooldown}. Its conditions stay " +
"unknown (Uncertain) until a lossless ConditionRefresh (RefreshRequired, reconnect, resubscribe, or a " +
"loss after the cool-down). The event item's revised queue size is {QueueSize}.",
_driverInstanceId, ras.Handle.DiagnosticId, b.Retries, reason, AlarmRefreshRetryCooldown,
ras.EventItem.Status?.QueueSize);
}
return false;
}
b.Retries++;
b.RetryPending = true;
b.LastRetryUtc = now;
var generation = ++b.RetryGeneration;
var delay = AlarmRefreshRetryBaseDelay * (1 << (b.Retries - 1));
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId}: {Reason}; re-running " +
"ConditionRefresh in {Delay} (attempt {Attempt}/{Max}).",
_driverInstanceId, ras.Handle.DiagnosticId, reason, delay, b.Retries, MaxAlarmRefreshRetries);
var sessionWork = _sessionWorkCts.Token;
_ = Task.Run(() => RetryAlarmRefreshAsync(ras, generation, delay, sessionWork));
return true;
}
/// <summary>#926: after <paramref name="delay"/>, re-run ConditionRefresh on <paramref name="ras"/> — only while it
/// is still the registered subscription for its handle (an unsubscribe / re-init releases it).</summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="generation">This retry's generation: only it may clear <c>RetryPending</c>.</param>
/// <param name="delay">The back-off.</param>
/// <param name="cancellationToken">The session's work token (cancelled by shutdown / re-init).</param>
/// <returns>A task completing when the refresh call returned (or was skipped).</returns>
private async Task RetryAlarmRefreshAsync(
RemoteAlarmSubscription ras, long generation, TimeSpan delay, CancellationToken cancellationToken)
{
var gateHeld = false;
try
{
if (delay > TimeSpan.Zero) await Task.Delay(delay, Clock, cancellationToken).ConfigureAwait(false);
await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false);
gateHeld = true;
if (!_alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) || !ReferenceEquals(current, ras)) return;
// From here a further loss may request the next retry: it belongs to THIS refresh's replay. That matters
// when the replay's own RefreshStart is lost too (queue still full) — without the reset, no bracket opens
// and nothing could request again. A lossy RefreshEnd of the PREVIOUS replay still in flight can then
// request one extra refresh; that is inside the bound.
ReleaseRetryPending(ras, generation, resetRequested: true);
if (AlarmRefreshRetryInvokerForTest is { } invoke)
await invoke(ras.Subscription, cancellationToken).ConfigureAwait(false);
else if (ras.Subscription.Session is not null && ras.Subscription.Created)
await TryConditionRefreshAsync(ras.Subscription, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) { /* shutdown / re-init: the subscription is being released */ }
catch (ObjectDisposedException) { /* driver disposed */ }
catch (Exception ex)
{
_logger.LogWarning(ex, "OpcUaClientDriver '{DriverInstanceId}': alarm re-refresh of {SubscriptionId} failed; " +
"its conditions stay unknown until a later lossless ConditionRefresh.",
_driverInstanceId, ras.Handle.DiagnosticId);
}
finally
{
// Only THIS retry's pending flag: a retry scheduled while the refresh call ran (a new generation) stands.
ReleaseRetryPending(ras, generation, resetRequested: false);
if (gateHeld)
{
try { _subscriptionGate.Release(); } catch (ObjectDisposedException) { }
}
}
}
/// <summary>#926: clear <c>RetryPending</c> if it still belongs to retry <paramref name="generation"/>.</summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="generation">The retry's generation.</param>
/// <param name="resetRequested">Also re-allow a retry request for the current bracket.</param>
private void ReleaseRetryPending(RemoteAlarmSubscription ras, long generation, bool resetRequested)
{
lock (_alarmStateLock)
{
if (ras.Bracket.RetryGeneration != generation) return;
ras.Bracket.RetryPending = false;
if (resetRequested) ras.Bracket.RetryRequestedSinceStart = false;
}
}
/// <summary>#926: a ConditionRefresh call on <paramref name="subscription"/> failed (not "unsupported"): no
/// RefreshEnd will come for it, so request a bounded re-refresh instead of waiting for the next external trigger.</summary>
/// <param name="subscription">The SDK alarm subscription.</param>
private void NoteConditionRefreshFailed(Subscription subscription)
{
foreach (var ras in _alarmSubscriptions.Values)
{
if (!ReferenceEquals(ras.Subscription, subscription)) continue;
lock (_alarmStateLock) _ = ScheduleAlarmRefreshRetryLocked(ras, "ConditionRefresh call failed");
}
}
/// <summary>1 while a RefreshRequired-triggered sweep is queued and has not started (coalescing).</summary>
private int _refreshRequiredSweepQueued;
/// <summary>
/// #926 (review r1 #7): a RefreshRequired asks for a refresh of every alarm subscription. Coalesced: while one
/// sweep is queued and not yet started, further RefreshRequired events add nothing (that sweep covers them). A
/// RefreshRequired arriving once the sweep has started queues the next one — it may report a later loss.
/// </summary>
private void RequestRefreshRequiredSweep()
{
if (Interlocked.CompareExchange(ref _refreshRequiredSweepQueued, 1, 0) != 0) return;
// Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh.
// r2 R2-1: bound to the session's work token, which a shutdown cancels first thing.
var sessionWork = _sessionWorkCts.Token;
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork,
onStart: () => Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0)));
}
/// <summary>True for a <c>RefreshRequiredEventType</c> event (the server asks the client to ConditionRefresh).</summary>
/// <param name="fields">The event's fields.</param>
/// <returns>Whether the event is a RefreshRequired marker.</returns>
@@ -2907,12 +3276,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId t
&& t == ObjectTypeIds.RefreshEndEventType;
private void RaiseInitialAlarmState(IReadOnlyList<string> refs, bool unsignalable)
private void RaiseInitialAlarmState(IReadOnlyList<string> refs, bool unsignalable, bool withdrawn = false)
{
if (refs.Count == 0) return;
try
{
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs, unsignalable));
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs, unsignalable, withdrawn));
}
catch (Exception ex)
{
@@ -2967,6 +3336,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
"OpcUaClientDriver '{DriverInstanceId}': ConditionRefresh on alarm subscription {SubscriptionId} failed; " +
"conditions already active upstream may not be reported until their next transition.",
_driverInstanceId, subscription.Id);
// #926 (review r1 #4): no RefreshEnd will come for this call — retry it, bounded.
NoteConditionRefreshFailed(subscription);
}
catch (OperationCanceledException)
{
@@ -2992,9 +3363,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// outage reach the host through the normal deduplicated path.
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <param name="onStart">Invoked first thing (the RefreshRequired coalescing flag's release).</param>
/// <returns>A task completing when every refresh call has returned.</returns>
private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken)
private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken, Action? onStart = null)
{
onStart?.Invoke();
if (_alarmSubscriptions.IsEmpty) return;
try
{
@@ -3146,6 +3519,9 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
if (fields.Count <= AlarmFieldConditionId) return null;
// ConditionRefresh brackets its re-delivery with RefreshStart/RefreshEnd — markers, never alarms.
if (IsRefreshMarker(UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]))) return null;
// #926: the server's queue-overflow notice is not an alarm either (pass-through would otherwise project it).
if (UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId et && et == ObjectTypeIds.EventQueueOverflowEventType)
return null;
// A condition BRANCH event reports a previous state with its own EventId: projecting it would flip the
// trunk's state, remembering it would make Acknowledge ack the branch.
if (fields.Count > AlarmFieldBranchId && UpstreamValueMapping.ToClr(fields[AlarmFieldBranchId]) is NodeId branch && !branch.IsNull)
@@ -3238,7 +3614,54 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
OpcUaAlarmSubscriptionHandle Handle,
MonitoredItem EventItem,
MonitoredItemNotificationEventHandler Handler,
IReadOnlyList<string> AlarmRefs);
IReadOnlyList<string> AlarmRefs)
{
/// <summary>#926: this subscription's ConditionRefresh bracket + bounded re-refresh state. Mutated only
/// under <c>_alarmStateLock</c>.</summary>
public AlarmRefreshBracket Bracket { get; } = new();
}
/// <summary>
/// #926 — the RefreshStart…RefreshEnd bracket of one alarm subscription. A RefreshEnd declares the conditions it
/// covers state-known (grpc-data A1), so it may only signal when the replay it closes is provably complete: its
/// RefreshStart was seen and no loss (EventQueueOverflow, RefreshRequired, a publish-sequence gap) was
/// observed since. Every field is read and written under <c>_alarmStateLock</c>.
/// </summary>
internal sealed class AlarmRefreshBracket
{
/// <summary>A RefreshStart was routed and its RefreshEnd not yet.</summary>
public bool Open;
/// <summary>The first loss observed since the last RefreshStart (null = none). A RefreshEnd with a loss
/// does not signal.</summary>
public string? LossSinceStart;
/// <summary>A re-refresh was already requested for the loss since the last RefreshStart or the last re-refresh's
/// start (so the lossy RefreshEnd that follows does not request a second one).</summary>
public bool RetryRequestedSinceStart;
/// <summary>A driver re-refresh is scheduled and has not started its ConditionRefresh call yet.</summary>
public bool RetryPending;
/// <summary>Driver re-refreshes spent since the last clean (signalled) RefreshEnd.</summary>
public int Retries;
/// <summary>The retry budget is spent and that was logged (once per episode).</summary>
public bool ExhaustedLogged;
/// <summary>Sequence number of the last delivered notification message (0 = none yet).</summary>
public uint LastSequenceNumber;
/// <summary>This subscription's conditions were declared known (a clean RefreshEnd) and no loss since: a loss
/// now must withdraw "known".</summary>
public bool Signalled;
/// <summary>When the last driver re-refresh was scheduled (cool-down of a spent budget).</summary>
public DateTime? LastRetryUtc;
/// <summary>Generation of the last scheduled re-refresh; only that retry may clear <see cref="RetryPending"/>.</summary>
public long RetryGeneration;
}
private sealed record OpcUaAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle
{
@@ -11,6 +11,11 @@ public sealed class DeferredProjectedNodeAccess(DeferredAddressSpaceSink deferre
definition = null;
return deferred.GetCapability<IProjectedNodeLookup>()?.TryResolve(nodeId, out definition) == true;
}
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
{
definition = null;
return deferred.GetCapability<IProjectedNodeLookup>()?.TryResolveForRenewal(nodeId, out definition) == true;
}
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId)
{
nodeId = null;
@@ -18,6 +18,20 @@ public interface IProjectedDemandLease : IDisposable
bool IsValid { get; }
}
/// <summary>
/// #922: how a refused <see cref="IProjectedDataAccess.TryAcquire"/> of a projected node is classified. A lapsed metadata
/// lease is NOT an authorization failure: only <see cref="Denied"/> is answered <c>BadUserAccessDenied</c>.
/// </summary>
public enum ProjectedLapseOutcome
{
/// <summary>Not a lapse the caller may wait out (no grant, not a lapse at all, or a revoked authority).</summary>
Denied,
/// <summary>The caller is granted the subject; its lapsed lease is being renewed (the task completes with the outcome).</summary>
Renewing,
/// <summary>The caller is granted the subject, but no renewal can run right now (capacity, a recent failure): retry later.</summary>
Unavailable,
}
/// <summary>Nonblocking local admission and bounded scheduling for projected data.</summary>
public interface IProjectedDataAccess
{
@@ -30,6 +44,17 @@ public interface IProjectedDataAccess
bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval);
/// <summary>Requests a coalesced fresh authenticated snapshot without changing caller ownership.</summary>
bool RequestFreshSnapshot(IProjectedDemandLease demand) => false;
/// <summary>
/// #922: classifies a refused acquire of <paramref name="nodeId"/> for <paramref name="operation"/> (Read or HistoryRead) and,
/// when the only reason is a lapsed lease the caller would otherwise be granted, starts (or joins) ONE bounded asynchronous
/// exact renewal. Nonblocking and lock-free with respect to the caller: never call it, or wait on the task, under the
/// node-manager <c>Lock</c> — the renewal commits through the SDK sink, which takes it.
/// </summary>
ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
{
renewal = null;
return ProjectedLapseOutcome.Denied;
}
/// <summary>True while a demand or physically retained operation still owns this projection.</summary>
bool HasLiveDemand(DataRealm realm, string localIdentifier) => true;
}
@@ -13,6 +13,12 @@ public interface IProjectedNodeLookup
{
bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition);
bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId);
/// <summary>
/// #922: the committed, still-live definition of a projected node WHETHER OR NOT its authority is current — used only to
/// renew a lapsed lease in place (the renewal re-proves authority at the origin and commits against this exact definition).
/// Confers nothing; never use it to serve.
/// </summary>
bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) { definition = null; return false; }
}
/// <summary>Installs and retires locally authorized mapping anchors.</summary>
@@ -4428,6 +4428,23 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
return false;
}
/// <summary>
/// #922: like <see cref="TryResolve"/> but WITHOUT the authority check, so a node whose metadata lease lapsed can be renewed
/// in place. Lock-free (committed snapshot), confers nothing.
/// </summary>
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
{
var committed = Volatile.Read(ref _committedProjectedDefinitions);
if (!_disposing && committed.TryGetValue(nodeId, out var current) && current.Lifetime.IsActive &&
Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest) && ReferenceEquals(current, latest))
{
definition = current;
return true;
}
definition = null;
return false;
}
private int _maxProjectedNodes = 4096;
private long _maxProjectedNodeBytes = 16 * 1024 * 1024;
private long _projectedNodeBytes;
@@ -6307,8 +6324,18 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (identity is null || access is null || !access.TryAcquire(projected.NodeId, identity, DataOperations.Read, out demand) ||
demand is null || !demand.IsValid)
{
errors[ii] = StatusCodes.BadUserAccessDenied;
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
demand?.Dispose(); demand = null;
// #922: a lapsed metadata lease is not an authorization failure. A caller granted the node gets the same
// retryable answer as a cold read while the lease renews on demand (off this thread, no Lock held).
var lapse = identity is null || access is null ? ProjectedLapseOutcome.Denied
: access.RenewLapsed(projected.NodeId, identity, DataOperations.Read, out _);
if (lapse == ProjectedLapseOutcome.Denied)
{
errors[ii] = StatusCodes.BadUserAccessDenied;
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
}
else values[ii] = new DataValue(Variant.Null, lapse == ProjectedLapseOutcome.Renewing
? StatusCodes.BadWaitingForInitialData : StatusCodes.BadResourceUnavailable);
continue;
}
ProjectedValueWrite? cached;
@@ -6349,6 +6376,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (Permits(identity, OpcUaOperation.Read, nodeToRead.NodeId)) continue;
nodeToRead.Processed = true;
// #922: an attribute of a projected node whose lease lapsed — retryable while it renews, never access-denied.
if (identity is not null && IsProjectedDescendant(nodeToRead.NodeId) && ProjectedDataAccess is { } lapsedAccess &&
ClassifyProjectedLapse(lapsedAccess, nodeToRead.NodeId, identity, DataOperations.Read) != ProjectedLapseOutcome.Denied)
{
values[ii] = new DataValue(Variant.Null, StatusCodes.BadResourceUnavailable);
continue;
}
errors[ii] = StatusCodes.BadUserAccessDenied;
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
denied++;
@@ -8935,18 +8969,75 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity
?? context.OperationContext?.UserIdentity as RoleCarryingUserIdentity;
var allowed = new List<NodeHandle>(nodesToProcess.Count);
foreach (var handle in nodesToProcess)
{
var veto = _authorizer?.AuthorizeIfRequired(
ServiceResult? Veto(NodeHandle handle) => _authorizer?.AuthorizeIfRequired(
identity, OpcUaOperation.HistoryRead, handle.NodeId, RealmOf(handle.NodeId), cached: false)
?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null);
?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null);
var vetoes = new ServiceResult?[nodesToProcess.Count];
var lapses = new ProjectedLapseOutcome?[nodesToProcess.Count];
var renewalTasks = new Task<bool>?[nodesToProcess.Count];
List<Task<bool>>? renewals = null;
var access = ProjectedDataAccess;
for (var i = 0; i < nodesToProcess.Count; i++)
{
var handle = nodesToProcess[i];
vetoes[i] = Veto(handle);
// #922: a projected node refused only because its metadata lease lapsed is renewed within this request — never
// answered access-denied for the lapse. A caller without the grant is classified Denied and never reaches the origin.
if (vetoes[i] is null || identity is null || access is null || !IsProjectedDescendant(handle.NodeId)) continue;
Task<bool>? renewal = null;
try { lapses[i] = access.RenewLapsed(handle.NodeId, identity, DataOperations.HistoryRead, out renewal); }
catch (Exception) { lapses[i] = ProjectedLapseOutcome.Denied; renewal = null; }
renewalTasks[i] = renewal;
if (renewal is not null) (renewals ??= []).Add(renewal);
}
if (renewals is not null)
{
// Block-bridged once per batch, like the projected history read itself; the SDK released Lock before dispatching.
// #922 review: the wait holds an SDK request thread, so it takes one of the SAME non-local history slots a projected
// read takes (never waiting for one — none free ⇒ the lapsed nodes are simply retryable), honours the request's
// cancellation, and is clearly longer than the renewal's own budget so a renewal that completes is never answered late.
var slots = GetNonLocalHistoryLimiter();
if (slots.Wait(0))
{
try
{
var wait = HistoryReadDeadline > TimeSpan.Zero && HistoryReadDeadline < ProjectedLapseRenewalWait
? HistoryReadDeadline : ProjectedLapseRenewalWait;
Task.WhenAll(renewals).Wait((int)wait.TotalMilliseconds,
context.OperationContext?.CancellationToken ?? CancellationToken.None);
}
catch (AggregateException) { }
catch (OperationCanceledException) { }
finally { slots.Release(); }
}
for (var i = 0; i < nodesToProcess.Count; i++)
if (lapses[i] is ProjectedLapseOutcome.Renewing) vetoes[i] = Veto(nodesToProcess[i]);
}
var allowed = new List<NodeHandle>(nodesToProcess.Count);
for (var i = 0; i < nodesToProcess.Count; i++)
{
var handle = nodesToProcess[i];
var veto = vetoes[i];
if (veto is null)
{
allowed.Add(handle);
continue;
}
// #922 review: the lapse classification and the veto are two authorities (DataOperationPolicy / DataPlaneAuthorizer).
// A renewal that SUCCEEDED and is still vetoed is a real refusal, never a retryable one.
if (lapses[i] is ProjectedLapseOutcome.Renewing && renewalTasks[i] is { IsCompletedSuccessfully: true, Result: true })
lapses[i] = ProjectedLapseOutcome.Denied;
if (lapses[i] is ProjectedLapseOutcome.Renewing or ProjectedLapseOutcome.Unavailable)
{
// Granted, but the lease could not be renewed in time (origin unreachable, capacity): retryable.
errors[handle.Index] = new ServiceResult(StatusCodes.BadResourceUnavailable);
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadResourceUnavailable };
continue;
}
// Set both slots explicitly rather than relying on the base's pre-seeded
// BadHistoryOperationUnsupported — "unsupported" would tell the client the node has no history,
// which is a different fact from "you may not read it" and sends them debugging the wrong thing.
@@ -8957,6 +9048,20 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
return allowed;
}
/// <summary>
/// #922: the longest a HistoryRead waits for the on-demand renewal of lapsed projected leases (one wait per batch, capped by
/// <see cref="HistoryReadDeadline"/>) — longer than the renewal's own budget (3 s), so a completed renewal is always seen.
/// </summary>
internal static readonly TimeSpan ProjectedLapseRenewalWait = TimeSpan.FromSeconds(4);
/// <summary>#922: classifies (and, when it is a lapse, starts renewing) a refused projected node; total — a fault is Denied.</summary>
private static ProjectedLapseOutcome ClassifyProjectedLapse(IProjectedDataAccess access, NodeId nodeId,
RoleCarryingUserIdentity identity, DataOperations operation)
{
try { return access.RenewLapsed(nodeId, identity, operation, out _); }
catch (Exception) { return ProjectedLapseOutcome.Denied; }
}
/// <inheritdoc />
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
protected override void HistoryReadRawModified(
@@ -55,6 +55,9 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
/// <inheritdoc />
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolve(nodeId, out definition);
/// <inheritdoc />
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolveForRenewal(nodeId, out definition);
/// <inheritdoc />
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) => _nodeManager.TryGetNodeId(namespaceUri, identifier, out nodeId);
@@ -19,7 +19,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// failover and re-deploys, identical on both pair members (the secret is a per-cluster <c>${secret:}</c>), and
/// equal across every listing and principal (m-T6), so a consumer dedupes a condition's Raw and UNS placements.
/// Being keyed, it cannot be dictionary-reversed from guessable RawPaths, and it carries no RawPath or driver id
/// (unlike <c>Metadata.stable_source_id</c>, #916).
/// (the v1 <c>Metadata.stable_source_id</c> did, and is no longer sent, #916).
/// </para>
/// <para>
/// Without a secret the origin advertises no <c>conditions</c> capability (fail closed): <see cref="IsAvailable"/>
@@ -13,11 +13,18 @@ internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, Cancel
internal DataTarget? Target => target;
internal object? BindingIdentity => bindingIdentity;
internal TimeSpan Remaining => remote.Remaining;
internal MetadataAuthorityLease Remote => remote;
internal TimeSpan UsableDuration => remote.UsableDuration;
private bool RouteAlive => !route.IsCancellationRequested && (routeCurrent?.Invoke() ?? true);
internal bool LiveContext => RouteAlive && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
internal bool ExpiredNaturally => remote.ExpiredNaturally && LiveContext;
public bool IsValid => LiveContext && remote.IsValid;
/// <summary>
/// #922: the authority is gone ONLY because it is transient — the remote lease's time ran out or its route was
/// replaced — while the local catalog authority, the mapping binding and the cache generation are all still current
/// and nothing revoked it. Such a lapse is renewed by an exact metadata refresh, never answered as an access denial.
/// </summary>
internal bool Renewable => !remote.Invalidated && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
internal ProjectionLeaseDiagnostics CaptureDiagnostics() => new(RouteAlive, local.IsActive,
remote.IsValid, bindingCurrent(), cache.IsCurrentGeneration(mapping, generation));
}
@@ -394,11 +394,19 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
long bytes = 256;
var maximum = Math.Min(request.Budget.MaxItems, limits.MaxPageItems);
var scanned = 0;
while (offset < children.Count && page.Count < maximum && scanned++ < maximum)
while (offset < children.Count && page.Count < maximum && scanned < maximum)
{
cancellationToken.ThrowIfCancellationRequested();
if (Expired(start, request.Budget)) return Task.FromResult(Empty(DataItemStatus.Unavailable));
var child = children[offset++];
// #917: an unsupported value node (an alarm-bearing tag, or a data type v1 cannot carry) is never listed. Every
// consumer build applies a browse page all-or-nothing and cannot materialise one, so listing it made the whole
// folder unbrowsable on the consumer (BadNoCommunication). It stays addressable (GetMetadata/Read/Subscribe on it
// answer Unsupported). An export rooted at it still compiles but grants nothing. A skipped node is not counted
// against the scan bound (it costs one check; the budget timeout above still bounds the call), so the skip never
// yields an empty Complete=false page.
if (child.Source is not null && !child.Supported) continue;
scanned++;
if ((request.Filter is { Length: > 0 } filter && !child.Metadata.BrowseName.Contains(filter, StringComparison.Ordinal))
|| !Allowed(catalog, context, child, DataOperations.Browse)) continue;
var metadata = Metadata(catalog, context, target, child);
@@ -92,11 +92,16 @@ public sealed partial class LocalExportCatalog
BackingSourceKey? source = null, DataValueKind valueKind = DataValueKind.Null, bool writable = false,
bool array = false, uint? length = null, bool supported = true, bool enabled = true)
{
writable &= supported; // #917 review: an unsupported value node is never writable, not even in internal metadata
var operations = source is null ? navigation : data | (writable ? DataOperations.Write : DataOperations.None);
var metadata = new DataMetadata(view, name, source is null ? "Folder" : supported ? "Variable" : "UnsupportedVariable",
array && supported ? DataValueKind.Array : valueKind, array && supported ? 1 : -1,
array && supported ? Array.AsReadOnly(new[] { length is { } n ? checked((int)n) : 0 }) : [],
writable, operations, serving.CatalogEpoch, source?.StableSourceId, null, false,
// #916: Metadata.stable_source_id is never sent. The internal key of a driver source is
// "<len>:<driverInstanceId><RawPath>" (SourceKey.ForDriver), which told a UNS-only peer the origin's driver ids
// and RawPaths; no consumer uses the field (it is optional on the wire and old consumers decode its absence as
// null). Acquisition keys on the LocalDataNode.Source BackingSourceKey, which is unchanged.
writable, operations, serving.CatalogEpoch, null, null, false,
array && supported ? valueKind : null);
nodes.Add(new(kind, id, metadata, scope, parent, source, supported, enabled));
views.Add((view.Realm, kind, id.ToUpperInvariant()), view);
@@ -131,7 +136,13 @@ public sealed partial class LocalExportCatalog
var enabled = deviceById[tagById[plan.TagId].DeviceId].Enabled && driverById[plan.DriverInstanceId].Enabled;
rawSources.Add(plan.NodeId, (source, enabled));
var kind = ValueKind(plan.DataType);
var supported = kind != DataValueKind.Unspecified && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
// #917: an alarm-bearing tag never gets a value (DriverHostActor keeps it out of the value fan-out; #896 gives it
// no UNS variable), so it is an unsupported value node: Browse does not list it (LocalDataServices) and every
// value operation answers Unsupported, instead of a Variable a consumer would wait on forever. The node is KEPT so
// an export rooted at it still compiles, but such a root grants nothing: its values are unsupported and its
// condition placement sits under its folder, not under the tag. The alarm is forwarded as a condition (A1–A4).
var supported = plan.Alarm is null && kind != DataValueKind.Unspecified
&& (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
var rawView = View(DataRealm.Raw, plan.NodeId, scope);
Add("RawTag", plan.TagId, plan.Name, rawView, scope, RawParent(scope), source,
supported ? kind : DataValueKind.Null, plan.Writable && (!plan.IsArray || plan.ArrayWritable),
@@ -47,6 +47,8 @@ public sealed class MetadataAuthorityLease : IDataAuthorizationLease
}
}
internal TimeSpan UsableDuration => _usableDuration;
/// <summary>True once <see cref="Invalidate"/> ran: a revocation, never renewable (#922).</summary>
internal bool Invalidated => Volatile.Read(ref _invalidated) != 0;
internal bool ExpiredNaturally => Volatile.Read(ref _invalidated) == 0 &&
_clock.GetElapsedTime(_requestStart, _clock.GetTimestamp()) >= _usableDuration;
public bool IsValid
@@ -22,6 +22,9 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
private readonly object _anchorGate = new();
private readonly ConcurrentDictionary<string, Installed> _installed = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<WorkKey, TaskCompletionSource> _inflight = new();
// #922 review: background refreshes of cached pages, keyed by the parent NODE (not caller / MaxResults), so varying the
// browse parameters cannot multiply origin browses of one parent.
private readonly ConcurrentDictionary<NodeId, byte> _refreshing = new();
private readonly record struct Failure(ProjectionPageStatus Status, long Until);
private readonly object _resultGate = new();
private readonly Dictionary<WorkKey, Failure> _failures = new();
@@ -176,15 +179,26 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
if (!guard.IsCurrent()) return Empty(ProjectedBrowseReadiness.Unavailable);
var retainedBytes = checked(sourceGuard.RetainedBytes + 2048L + 2L * (snapshot.Continuation?.Length ?? 0) +
expectedIds.Sum(node => 128L + 2L * node.IdentifierAsString.Length));
// #922: a re-browse served from a cached page must still renew a lease that is running out — otherwise a client that
// re-browses to refresh a node it reads gets nothing until the page itself lapses. Past half its life an initial page
// is served as is AND refreshed in the background (at most one in flight per page key; a fresh page is untouched).
if (input.Cursor is null && lease is BoundProjectionLease bound && bound.Remaining < bound.UsableDuration / 2)
_ = TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: true);
return new(ProjectedBrowseReadiness.Ready, Array.AsReadOnly(expectedIds), snapshot.Continuation, snapshot.Complete,
guard.IsCurrent, retainedBytes);
}
if (snapshot.Status == ProjectionPageStatus.InvalidContinuation) return Empty(ProjectedBrowseReadiness.InvalidContinuation);
var key = new WorkKey(input.Parent, identity, input.Cursor, maximum);
return TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: false);
}
private ProjectedBrowsePage TrySchedule(WorkKey key, ProjectedBrowseRequest request, Installed anchor, NodeId exactParent, bool refresh)
{
lock (_resultGate)
{
var now = _catalog.Clock.GetTimestamp();
foreach (var expired in _failures.Where(x => x.Value.Until <= now).Select(x => x.Key).ToArray()) _failures.Remove(expired);
if (refresh && (_failures.ContainsKey(key) || _inflight.ContainsKey(key) || !_refreshing.TryAdd(exactParent, 0)))
return Empty(ProjectedBrowseReadiness.Pending);
if (_failures.TryGetValue(key, out var failure))
return Empty(failure.Status switch
{
@@ -193,11 +207,14 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
_ => ProjectedBrowseReadiness.Unavailable
});
if (_inflight.ContainsKey(key)) return Empty(ProjectedBrowseReadiness.Pending);
if (_failures.Count + _pending >= _maxPending) return Empty(ProjectedBrowseReadiness.Unavailable);
if (!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously))) return Empty(ProjectedBrowseReadiness.Pending);
if (_failures.Count + _pending >= _maxPending ||
!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)))
{
if (refresh) _refreshing.TryRemove(exactParent, out _);
return Empty(_failures.Count + _pending >= _maxPending ? ProjectedBrowseReadiness.Unavailable : ProjectedBrowseReadiness.Pending);
}
_pending++;
}
var exactParent = input.Parent;
_ = Task.Run(async () =>
{
var result = ProjectionPageStatus.Unavailable;
@@ -208,6 +225,7 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
lock (_resultGate)
{
_inflight.TryRemove(key, out var completed);
if (refresh) _refreshing.TryRemove(exactParent, out _);
_pending--;
if (result != ProjectionPageStatus.Ready && !_stop.IsCancellationRequested)
{
@@ -106,7 +106,8 @@ public sealed class ProjectedCatalogCache
private static ParentKey Key(ProjectedBrowseRequest request) => new(request.MappingId.ToUpperInvariant(), request.Parent,
request.Filter, request.Continuation, request.Caller, request.ConfiguredCapability);
private static (string Mapping, DataView Parent) Parent(string mapping, DataView parent) => (mapping.ToUpperInvariant(), parent);
private bool ValidCore(ProjectedNodeProof proof) => proof.Generation > 0 && proof.Lease.IsValid && proof.Lease.Serving.ServingGeneration > 0 &&
private bool ValidCore(ProjectedNodeProof proof, bool requireLease = true) => proof.Generation > 0 &&
(requireLease ? proof.Lease.IsValid : proof.Lease is BoundProjectionLease { Renewable: true }) && proof.Lease.Serving.ServingGeneration > 0 &&
proof.Subject.Serving == proof.Lease.Serving && proof.Metadata.View == proof.Subject.View &&
proof.Metadata.Serving == proof.Lease.Serving && proof.OriginMetadata.Serving == proof.Lease.Serving &&
proof.OriginMetadata.View.MappingId is null && proof.OriginMetadata.View.MappingRevision == 0 &&
@@ -488,6 +489,26 @@ public sealed class ProjectedCatalogCache
proof = null; return false;
}
}
/// <summary>
/// #922: the retained, non-retired proof of a node whose authority may be refreshed by an exact renewal — a valid one,
/// or one that is invalid ONLY because its lease lapsed (time, or a replaced route) while every local fence still holds
/// (<see cref="BoundProjectionLease.Renewable"/>). Never an authorization: the caller still authorizes the subject and
/// the renewal re-proves everything at the origin before anything is served.
/// </summary>
internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof)
{
lock (_sync)
{
if (_nodes.TryGetValue((realm, localId), out var entry) && !entry.Retired && (Valid(entry.Proof) || Renewable(entry.Proof)))
{ proof = entry.Proof; return true; }
proof = null; return false;
}
}
private bool Renewable(ProjectedNodeProof proof)
{
try { return ValidCore(proof, requireLease: false); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; }
}
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin)
{
lock (_sync)
@@ -93,7 +93,7 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC
/// <summary>
/// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a
/// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's
/// node-only harness measured 160,997). A3b review S5: the WORST case — two placements, every EventId slot, three
/// node-only harness retains 79,085 B on the same method, #929 — its original 160,997 was a <c>GC.GetTotalMemory</c> delta). A3b review S5: the WORST case — two placements, every EventId slot, three
/// event items, the runner's Live + Buffer records. A3 review round 2: measured with the retained heap
/// (<c>GCMemoryInfo</c>, not <c>GC.GetTotalMemory</c>, which counted ~125 MiB of committed-but-free regions) and the
/// settled working set, 8 EventId slots (§5.6): max of three runs = 158,629 B (working set; heap 111,715 B), rounded up.
@@ -19,6 +19,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
public TimeProvider Clock { get; }
internal Func<TimeSpan, TimeSpan>? RetryJitterForTests { get; set; }
internal Action? BeforeSuccessorAdoptionForTests { get; set; }
/// <summary>#920: runs on the stream pump after a publish passed its demand check, before the duplicate-baseline check.</summary>
internal Action<IProjectedDemandLease>? AfterPublishDemandCheckForTests { get; set; }
private readonly IFederatedProjectionCatalog _catalog;
private readonly IProjectedNodeLookup _nodes;
private readonly Func<string, string?> _connectionForMapping;
@@ -201,6 +203,123 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireException); return false; }
}
// #922: at most one on-demand renewal per projected node AND operation (each requests its own bit at the origin); a failed
// one is not retried for a short back-off so a client polling a node whose origin is unreachable cannot turn every Read into
// a metadata call. Renewals never use the unary budget (that would starve cold reads, writes and subscription renewals):
// they queue — at most MaxQueuedLapseRenewals — for the resolver's own on-demand pool, so a batch of N lapsed nodes renews
// them all, a few at a time.
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task<bool>> _lapseRenewals = new();
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), long> _lapseRenewalBackoff = new();
private const int MaxLapseRenewalBackoffEntries = 4096;
internal const int MaxQueuedLapseRenewals = 64;
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
/// <summary>The whole on-demand renewal, pool wait included; clearly shorter than the longest a HistoryRead waits for it.</summary>
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(3);
/// <summary>One metadata item and its capability probe: never a multi-MiB unary reservation.</summary>
internal const long LapseRenewalBytes = 256 * 1024;
internal int LapseRenewalsStartedForTests => Volatile.Read(ref _lapseRenewalsStarted);
private int _lapseRenewalsStarted;
/// <inheritdoc />
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
{
renewal = null;
if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead) || _renewalSink is not { } sink ||
_catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
try
{
// The SDK node must still be live, and either it or its catalog proof must have lapsed — a refusal of a node whose
// authority is fully current was a real refusal (grant, capacity…), never a lapse.
if (!_nodes.TryResolveForRenewal(nodeId, out var definition) || definition is null || !definition.Lifetime.IsActive ||
!resolver.TryResolveForRenewal(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
definition.AuthorityIsCurrent() && _catalog.IsUsableProof(proof) ||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
proof.Metadata.View.MappingId is not { } mapping || _connectionForMapping(mapping) is not { Length: > 0 } ||
(operation == DataOperations.Read && proof.MaximumSampleAge <= TimeSpan.Zero) ||
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))))
return ProjectedLapseOutcome.Denied;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
// The same grant the served operation needs, judged on everything but the lapsed lease: a caller without it is
// refused exactly as before, and never causes an origin call.
if (!_policy.AuthorizeMappedSubject(identity, Operation(operation), proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver))
return ProjectedLapseOutcome.Denied;
var key = (definition.Realm, definition.LocalIdentifier, operation);
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
TaskCompletionSource<bool> started;
lock (_sync)
{
if (_disposed) return ProjectedLapseOutcome.Unavailable;
if (_lapseRenewals.TryGetValue(key, out var running)) { renewal = running; return ProjectedLapseOutcome.Renewing; }
var now = Clock.GetTimestamp();
if (_lapseRenewalBackoff.TryGetValue(key, out var until))
{
if (now < until) return ProjectedLapseOutcome.Unavailable;
_lapseRenewalBackoff.Remove(key);
}
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_lapseRenewals.Add(key, started.Task);
}
Interlocked.Increment(ref _lapseRenewalsStarted);
// Never on the caller's thread: the renewal awaits the origin and commits through the SDK sink (node-manager Lock).
_ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, caller, identity, operation, budget, started));
renewal = started.Task;
return ProjectedLapseOutcome.Renewing;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return ProjectedLapseOutcome.Denied; }
}
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
(DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<bool> completion)
{
var renewed = false;
try
{
renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
finally
{
lock (_sync)
{
_lapseRenewals.Remove(key);
if (!renewed && !_disposed)
{
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
}
}
}
// A Read answered retryable while the lease renewed: fetch the value now, through the ordinary authorized path, so the
// client's retry is served from the fresh sample instead of starting another cold read.
if (renewed && operation == DataOperations.Read)
{
IProjectedDemandLease? demand = null;
try
{
if (TryAcquire(nodeId, caller, DataOperations.Read, out demand) && demand is not null &&
ScheduleRead(demand, new DataBudget(LapseRenewalTimeout, 1, ProjectedReadBytes), Clock.GetTimestamp())) demand = null;
}
catch (Exception ex) when (ex is not OutOfMemoryException) { }
finally { demand?.Dispose(); }
}
completion.TrySetResult(renewed);
}
// Full map (rare): drop the expired entries; if none expired, the one that expires first — never the whole map, which would
// let every node's back-off lapse at once.
private void EvictLapseBackoffLocked()
{
var now = Clock.GetTimestamp();
var expired = _lapseRenewalBackoff.Where(entry => entry.Value <= now).Select(entry => entry.Key).ToArray();
foreach (var key in expired) _lapseRenewalBackoff.Remove(key);
if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value).Key);
}
/// <summary>The per-read byte budget the SDK Read path schedules a cold projected read with.</summary>
internal const long ProjectedReadBytes = 4 * 1024 * 1024;
internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand)
{
demand = null;
@@ -568,7 +687,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
internal bool HasFreshCachedLocked(Demand demand)
{
var sample = _cachedSample;
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !demand.IsValid || !IsValid) return false;
// #920: deliberately NOT gated on demand.IsValid. This answers "is the sample already published for this version
// still fresh at this demand's age limit" — the duplicate-baseline suppression in Publish. A demand disposed
// concurrently (a failed SDK item construction) used to turn the answer into "not fresh", so a dying
// registration re-published the same acquisition as a new complete baseline to every item on the node.
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !IsValid) return false;
try
{
return sample.OriginAgeBounds.Advance(_owner.Clock.GetElapsedTime(sample.ReceivedTimestamp,
@@ -1658,6 +1781,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
validated = false;
if (registration.Removed || !registration.Demand.IsValid || update.SourceProof is not AttemptProof proof) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
_owner.AfterPublishDemandCheckForTests?.Invoke(registration.Demand);
var source = proof.Source;
if (!source.TryPrepareSuccessor(registration.Demand, out var successor)) return false;
try
@@ -1675,6 +1799,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
validated = update.IsCompleteSnapshot;
if (version == source.LastVersion && update.IsCompleteSnapshot && !registration.Recovery &&
source.HasFreshCachedLocked(registration.Demand)) return false;
// A demand disposed since the check above publishes nothing (it is no longer anyone's subscription).
if (!registration.Demand.IsValid) { validated = false; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
if (_owner._publisher.TryPublish([update]))
{
if (successor is not null)
@@ -22,6 +22,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
private readonly DataOperationPolicy _policy;
private readonly int _maxMappings;
private readonly SemaphoreSlim _fetchSlots;
// #922 review: on-demand renewals of lapsed nodes (a Read / HistoryRead) run on their OWN small pool, never on _fetchSlots,
// so a burst of them cannot crowd out browse pages or the subscription renewals that keep live items from lapsing.
private readonly SemaphoreSlim _onDemandSlots;
internal int OnDemandRenewalSlots { get; }
private readonly int _maximumWaiters;
private readonly Func<CancellationToken, Task>? _beforeFetch;
private int _waiterCount;
@@ -44,6 +48,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
_source = source ?? throw new ArgumentNullException(nameof(source)); _policy = policy ?? throw new ArgumentNullException(nameof(policy));
if (maxMappings <= 0 || maxConcurrentFetches <= 0) throw new ArgumentOutOfRangeException(nameof(maxMappings));
_maxMappings = maxMappings; _fetchSlots = new(maxConcurrentFetches, maxConcurrentFetches);
OnDemandRenewalSlots = Math.Max(1, maxConcurrentFetches / 2);
_onDemandSlots = new(OnDemandRenewalSlots, OnDemandRenewalSlots);
_maximumWaiters = checked(maxConcurrentFetches * 16);
_cache.Invalidated += OnInvalidated;
}
@@ -98,6 +104,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof);
public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof);
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin);
internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof) =>
_cache.TryResolveForRenewal(realm, localId, out proof);
internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) =>
_cache.TryPinExpiredRecoveryPair(previous, successor, out pin);
public async Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
@@ -301,8 +309,14 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
// page, cursor or sibling visibility and does not create a physical subscription.
internal async Task<bool> RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured,
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false)
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false,
OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe,
bool onDemand = false)
{
// #922: a subscription renews for CreateMonitoredItems/Subscribe (the default); an on-demand renewal of a lapsed node
// renews for the operation the caller is performing (Read / HistoryRead) and requires exactly that bit at the origin.
if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead) ||
required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead)) return false;
var mapping = previous.Metadata.View.MappingId;
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false;
ProjectedMappingBinding binding;
@@ -313,7 +327,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
bool CallerAllowed() => demandActive() && (configured is not null
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
: caller is not null && _policy.IsCallerUsable(caller) &&
_policy.AuthorizeLocal(caller, OpcUaOperation.CreateMonitoredItems, previous.Subject.Scope));
_policy.AuthorizeLocal(caller, authorizeAs, previous.Subject.Scope));
if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() ||
previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm ||
previous.OriginMetadata.View.MappingId is not null ||
@@ -322,7 +336,17 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count ||
!previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) ||
!previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return false;
if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return false;
// A subscription renewal never queues (it retries on its own cadence); an on-demand renewal waits for its own pool within
// its budget, and the wait is charged to that budget.
var slots = onDemand ? _onDemandSlots : _fetchSlots;
var queued = System.Diagnostics.Stopwatch.GetTimestamp();
if (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) return false;
if (onDemand)
{
var left = budget.Timeout - System.Diagnostics.Stopwatch.GetElapsedTime(queued);
if (left <= TimeSpan.Zero) { slots.Release(); return false; }
budget = budget with { Timeout = left };
}
IGrpcDataAdapterConnectionLease? connection = null;
try
{
@@ -356,7 +380,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank ||
metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind ||
!metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) ||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & DataOperations.Subscribe) == 0 ||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & required) == 0 ||
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false;
metadata.Validate(); remoteLease.Validate();
var generation = _cache.CaptureGeneration(mapping);
@@ -377,7 +401,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata,
TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
var guard = new ExactAuthority(renewed);
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, authorizeAs,
mapped.View, serving, subject, resolver, lease)) return false;
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) };
@@ -400,7 +424,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
finally { _fetchSlots.Release(); }
finally { slots.Release(); }
}
}
public void Dispose()
@@ -213,6 +213,31 @@ public sealed partial class DriverHostActor
return;
}
if (msg.Args.Withdrawn)
{
// #926: the source lost events after establishing these conditions. Take "known" back (same chain as its
// projections, so it lands after them), keep them out of the backstop (which would re-mark them known by
// timer), and put them back in the F5 window so a source that never re-signals is diagnosed.
t.Unsignalable.ExceptWith(msg.Args.ConditionIds);
var withdrawn = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds, known: false);
if (t.GoodSinceUtc is not null && _alarmRefsByDriver.TryGetValue(msg.DriverInstanceId, out var owned))
{
var ownedPaths = owned.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal);
var before = t.Pending.Count;
t.Pending.UnionWith(msg.Args.ConditionIds.Where(ownedPaths.Contains));
// An F5 window already running covers them; otherwise start one now. A diagnostic already raised for
// that window must count them too (#926 review r2).
if (t.Pending.Count != before)
{
if (t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t);
else if (t.DiagnosticRaised) _conditionSignals.Hub?.UpdateUnsignalled(msg.DriverInstanceId, t.Pending.Count);
}
}
_log.Info("DriverHost {Node}: driver {Driver} withdrew {Count} condition(s) ({Routed} routed) — state no longer known (events lost)",
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, withdrawn);
return;
}
if (msg.Args.Unsignalable)
{
// InitialStateUnsignalable: no real signal will come. Only a driver type with a backstop (OpcUaClient) marks
@@ -327,7 +352,7 @@ public sealed partial class DriverHostActor
}
/// <summary>Route driver condition ids (RawPaths) to their condition nodes and send one mark per realm.</summary>
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds)
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds, bool known = true)
{
if (_opcUaPublishActor is null || conditionIds.Count == 0) return 0;
var byRealm = new Dictionary<AddressSpaceRealm, List<string>>();
@@ -344,7 +369,7 @@ public sealed partial class DriverHostActor
var count = 0;
foreach (var (realm, ids) in byRealm)
{
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm));
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm, Known: known));
count += ids.Count;
}
@@ -3121,7 +3121,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// <see cref="HandleArtifactForApply"/>, the continuation both modes share.
/// </summary>
/// <remarks>
/// Both begin-paths arm the <see cref="ApplyWedgeTimerKey"/> watchdog, because both leave the
/// Both begin-paths arm the <see cref="ApplyWedgeTimerKey"/> watchdog — after the synchronous
/// Applying-row write, immediately before the read/fetch starts — because both leave the
/// host alive and dequeuing while it waits for bytes it does not have yet — which is exactly
/// what makes a silent wedge possible. (Before the Direct read moved off the mailbox this was
/// the only such path: an inline read could not be "stuck in Applying" in any sense a watchdog
@@ -3131,7 +3132,6 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
{
_applyingDeploymentId = deploymentId;
Become(Applying);
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
// Persist Applying row (idempotent on PK) — same crash-boundary marker as the Direct apply.
UpsertNodeDeploymentState(deploymentId, NodeDeploymentStatus.Applying, failureReason: null);
@@ -3152,6 +3152,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_log.Debug("DriverHost {Node}: fetching artifact for {Id} (rev {Rev}) from central over gRPC",
_localNode, deploymentId, revision);
// Armed only now, AFTER the synchronous Applying-row write above and immediately before the
// read/fetch starts: the watchdog times the read/fetch (its Warning says so), and a slow row write
// armed-before enqueued the tick ahead of the fetch's pipe-back, reporting a fetch that answered at
// once as WEDGED (Runtime.Tests master failures: ACompletedApply_NeverReportsAWedge on a cold EF model).
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
// A faulted fetch task maps to null bytes — the apply-failure path, exactly like an
// all-endpoints-down fetch — so a fault can never escape as an unhandled actor message.
_artifactFetcher.FetchAsync(deploymentId.ToString(), revision.Value, CancellationToken.None)
@@ -3190,7 +3196,6 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
{
_applyingDeploymentId = deploymentId;
Become(Applying);
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
// Persist Applying row (idempotent on PK) — the crash-boundary marker, and deliberately still
// on the actor thread: one bounded row write, and the apply must be recorded as in flight
@@ -3200,6 +3205,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_log.Debug("DriverHost {Node}: reading artifact for {Id} (rev {Rev}) from the ConfigDb, off the mailbox",
_localNode, deploymentId, revision);
// Armed after the Applying-row write, immediately before the read starts — see BeginFetchAndCacheApply.
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
Task.Run(() => LoadArtifactBlob(deploymentId))
.PipeTo(
Self,
@@ -238,7 +238,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <see cref="AttributeAlarmPublished"/>, so it reaches <see cref="DriverHostActor"/> after every alarm event the
/// driver raised before it.</summary>
/// <remarks>A1 review S2: <paramref name="ConnectionEpoch"/> is the connection (Connected entry) the driver raised
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge.</remarks>
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge. #926: keep this message
/// IN-PROCESS (child → parent only) — it carries <see cref="AlarmInitialStateEventArgs"/> by reference, and a
/// serialized copy that dropped <c>Withdrawn</c> would default it to false and turn a withdrawal into a "known" mark.</remarks>
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args,
long? ConnectionEpoch = null);
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch);
@@ -1165,47 +1165,89 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying {Count} deferred status writes threw", statuses.Count); }
}
// G3 pre-pass: a deferred projection outside the applied scope is skipped — its source's KNOWN marks are discarded
// wherever they sit in the arrival order (the conservative reading of "never known over a projection that did
// not land").
foreach (var (alarm, _) in _deferred.Alarms)
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) _deferred.NoteAlarmLoss(alarm.Source);
// #926 review r2: alarm states, alarm qualities and condition-known marks replay as ONE list in ARRIVAL order.
// Marks used to replay after every alarm, which was right for a "known" mark (it summarises the projections
// before it) but wrong for a withdrawal followed by a live transition: replayed transition-then-withdrawal,
// the condition ended unknown although the transition had re-established it — and the host, which saw the
// transition last, no longer counted it in F5. Arrival order is exactly what the live path applies.
var items = new List<(long Seq, int Kind, int Index)>();
var alarmList = _deferred.Alarms.ToList();
var qualityList = _deferred.AlarmQualities.ToList();
var markList = _deferred.Marks.ToList();
for (var i = 0; i < alarmList.Count; i++) items.Add((alarmList[i].Seq, 0, i));
for (var i = 0; i < qualityList.Count; i++) items.Add((qualityList[i].Seq, 1, i));
for (var i = 0; i < markList.Count; i++) items.Add((markList[i].Seq, 2, i));
items.Sort((x, y) => x.Seq.CompareTo(y.Seq));
var alarms = 0;
foreach (var alarm in _deferred.Alarms)
{
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId)))
{
_deferred.NoteAlarmLoss(alarm.Source); // G3: a skipped projection — the source's marks go too
continue;
}
alarms++;
try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
}
var qualities = 0;
foreach (var quality in _deferred.AlarmQualities)
{
if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
qualities++;
try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
}
// A1 F2/G3: the deferred "known" marks replay LAST, after every deferred alarm — and only for a source none of
// whose deferred projections was dropped or skipped. A discarded mark leaves its conditions unknown (Uncertain)
// until the source's next signal.
var marks = 0;
var discarded = 0;
foreach (var (mark, sender) in _deferred.Marks)
var discardedBySender = new Dictionary<(string Source, AddressSpaceRealm Realm), (IActorRef? Sender, List<string> Ids)>();
// Consecutive marks of one (source, realm, known) are applied as one sink call.
string? runSource = null;
AddressSpaceRealm runRealm = default;
var runKnown = false;
var runIds = new List<string>();
void FlushRun()
{
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
if (mark.Known && _deferred.SourceLost(mark.Source))
if (runIds.Count == 0) return;
marks++;
ApplyMark(new MarkConditionsKnown(runSource!, runIds.ToList(), runRealm, runKnown));
runIds.Clear();
}
foreach (var (_, kind, index) in items)
{
if (kind == 2)
{
discarded++;
TellDiscarded(sender, new ConditionMarksDiscarded(mark.Source, mark.ConditionIds, mark.Realm));
var m = markList[index];
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
if (m.Known && _deferred.SourceLost(m.Source))
{
discarded++;
if (!discardedBySender.TryGetValue((m.Source, m.Realm), out var d))
discardedBySender[(m.Source, m.Realm)] = d = (m.Sender, new List<string>());
d.Ids.Add(m.ConditionId);
continue;
}
if (runIds.Count > 0 && (runSource != m.Source || runRealm != m.Realm || runKnown != m.Known)) FlushRun();
runSource = m.Source;
runRealm = m.Realm;
runKnown = m.Known;
runIds.Add(m.ConditionId);
continue;
}
marks++;
ApplyMark(mark);
FlushRun();
if (kind == 0)
{
var alarm = alarmList[index].Msg;
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) continue; // counted in the pre-pass
alarms++;
try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
}
else
{
var quality = qualityList[index].Msg;
if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
qualities++;
try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
}
}
FlushRun();
foreach (var ((source, realm), (sender, ids)) in discardedBySender)
TellDiscarded(sender, new ConditionMarksDiscarded(source, ids, realm));
// N1: a KNOWN mark that did not fit the deferral was dropped (staying unknown is safe) — its sender hears it.
foreach (var (source, sender) in _deferred.OverflowedMarkSources)
@@ -1233,6 +1275,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// the two live writes leave on the node). Bounded by <see cref="Capacity"/> distinct keys across all kinds;
/// beyond it a NEW key is not held (an existing key still updates), counted in <see cref="Dropped"/>.
/// </summary>
/// <summary>One deferred condition-known mark (#926 review r2: per condition, with its arrival sequence).</summary>
private sealed record DeferredMark(
string Source, string ConditionId, AddressSpaceRealm Realm, bool Known, IActorRef? Sender, long Seq);
private sealed class DeferredWrites(int capacity)
{
private struct VariableEntry
@@ -1246,11 +1292,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new();
private readonly Dictionary<(AddressSpaceRealm, string), AlarmStateUpdate> _alarms = new();
private readonly Dictionary<(AddressSpaceRealm, string), AlarmQualityUpdate> _qualities = new();
// A1: condition-known marks in arrival order (bounded by Capacity — a dropped mark only keeps conditions
// unknown, which is always safe), and the sources that lost a deferred alarm projection (G3).
private readonly List<(MarkConditionsKnown Msg, IActorRef? Sender)> _marks = new();
private readonly Dictionary<(AddressSpaceRealm, string), (AlarmStateUpdate Msg, long Seq)> _alarms = new();
private readonly Dictionary<(AddressSpaceRealm, string), (AlarmQualityUpdate Msg, long Seq)> _qualities = new();
// A1 / #926 review r2: the LATEST condition-known mark per (realm, condition id), with its arrival sequence, and
// the sources that lost a deferred alarm projection (G3). Per-condition, so a withdrawal-heavy plan window holds
// at most one entry per condition (bounded by the address space), and replay can interleave marks with alarm
// states in arrival order.
private readonly Dictionary<(AddressSpaceRealm, string), DeferredMark> _marks = new();
private long _seq;
private readonly Dictionary<string, IActorRef?> _overflowedMarkSources = new(StringComparer.Ordinal);
private readonly HashSet<string> _lossySources = new(StringComparer.Ordinal);
private bool _unattributedLoss;
@@ -1259,20 +1308,31 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
public long Dropped { get; private set; }
public int Count => _variables.Count + _alarms.Count + _qualities.Count;
public bool IsEmpty => Count == 0 && _marks.Count == 0;
public IEnumerable<AlarmStateUpdate> Alarms => _alarms.Values;
public IEnumerable<AlarmQualityUpdate> AlarmQualities => _qualities.Values;
public IReadOnlyList<(MarkConditionsKnown Msg, IActorRef? Sender)> Marks => _marks;
public IEnumerable<(AlarmStateUpdate Msg, long Seq)> Alarms => _alarms.Values;
public IEnumerable<(AlarmQualityUpdate Msg, long Seq)> AlarmQualities => _qualities.Values;
public IEnumerable<DeferredMark> Marks => _marks.Values;
/// <summary>
/// Defer a mark. A withdrawal (<c>Known: false</c>) is never dropped — review round 2 N1: staying KNOWN over a
/// lost withdrawal is the unsafe direction, and withdrawals are bounded by connectivity edges. A known mark
/// beyond <see cref="Capacity"/> is dropped (unknown is safe) and its source is remembered so the sender hears
/// of it at replay (N2).
/// Defer a mark, per condition: a later mark of the same condition replaces the earlier (the later one is what
/// the live path leaves). A withdrawal (<c>Known: false</c>) is never dropped — review round 2 N1: staying KNOWN
/// over a lost withdrawal is the unsafe direction. It is bounded anyway: one entry per condition, so at most
/// the number of conditions in the address space (#926 made withdrawals routine, so the old "bounded by
/// connectivity edges" no longer held). A known mark for a NEW condition beyond <see cref="Capacity"/> marks is
/// dropped (unknown is safe) and its source is remembered so the sender hears of it at replay (N2).
/// </summary>
public void Mark(MarkConditionsKnown msg, IActorRef? sender)
{
if (!msg.Known || _marks.Count < Capacity) _marks.Add((msg, sender));
else _overflowedMarkSources[msg.Source] = sender;
foreach (var id in msg.ConditionIds)
{
if (string.IsNullOrEmpty(id)) continue;
var key = (msg.Realm, id);
if (msg.Known && !_marks.ContainsKey(key) && _marks.Count >= Capacity)
{
_overflowedMarkSources[msg.Source] = sender;
continue;
}
_marks[key] = new DeferredMark(msg.Source, id, msg.Realm, msg.Known, sender, ++_seq);
}
}
public IEnumerable<(string Source, IActorRef? Sender)> OverflowedMarkSources =>
@@ -1325,12 +1385,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
public bool Alarm(AlarmStateUpdate msg)
{
var key = (msg.Realm, msg.AlarmNodeId);
if (!Put(_alarms, key, msg)) return false;
if (!Put(_alarms, key, (msg, _seq + 1))) return false;
_seq++;
_qualities.Remove(key);
return true;
}
public bool AlarmQuality(AlarmQualityUpdate msg) => Put(_qualities, (msg.Realm, msg.AlarmNodeId), msg);
public bool AlarmQuality(AlarmQualityUpdate msg)
{
if (!Put(_qualities, (msg.Realm, msg.AlarmNodeId), (msg, _seq + 1))) return false;
_seq++;
return true;
}
public (List<ValueWrite> Values, List<StatusWrite> Statuses) VariableWrites(Func<(AddressSpaceRealm, string), bool> include)
{
@@ -1357,6 +1423,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
_lossySources.Clear();
_unattributedLoss = false;
Dropped = 0;
_seq = 0;
}
private bool Put<T>(Dictionary<(AddressSpaceRealm, string), T> map, (AddressSpaceRealm, string) key, T value)