fix(grpc-data): A4 #930/#931 — in-stream condition retries (no refresh storm), ConditionCapacity recovery, reconnect backoff, ledger, single RefreshRequired, parked-runner release; condition diagnostics core

#930 N2: an Unavailable mapping (refused item, failed root, snapshot timeout) is retried on the OPEN stream by
re-adding its item (AddSubscriptionItems) on its own backoff — definitive refusals (Denied/NotFound/Unsupported)
on LongRetryDelay (5 min, doubling to 4x), transient ones on the snapshot timeout x 2^n (<= 8x) — so healthy
mappings are never re-snapshotted for it; an incomplete barrier whose incomplete set equals the previous barrier's
sends no RefreshRequired. N3: ConditionCapacity is retried in-stream on the long timer and recovers.
#931 N4 exponential reconnect backoff (MaxReconnectDelay 60 s); N5 held-but-unlisted keys charged beside known
claims (overlapping unknown ones) + SetMaterialised cap report; N6 method calls read Serving without _gate;
N7 a capacity reset that removed conditions sends no second RefreshRequired; N8 a parked runner is released once
its removal finished.
A4 diagnostics core: DataConnectionConditionDiagnostics (side-labelled items/resyncs/capacity/method metrics, new
refresh_required counter, consumer + origin evidence), Commons contracts, DI + deployment-runtime + driver-host wiring.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-24 23:03:53 -05:00
parent 9143804987
commit 78eb98ea13
15 changed files with 920 additions and 105 deletions
@@ -48,7 +48,48 @@ public sealed record DataConnectionDiagnosticsSnapshot(
long? HistoryReadsGood = null,
long? HistoryReadsUncertain = null,
long? HistoryReadsBad = null,
int? OpenRemoteContinuations = null);
int? OpenRemoteContinuations = null,
// A4 consumer-side imported-condition evidence (null = no condition-bearing mapping on this connection, or an older sender).
ConsumerConditionDiagnostics? Conditions = null);
/// <summary>A4: one condition-bearing mapping of a consumer connection's condition stream.</summary>
/// <param name="MappingId">The mapping.</param>
/// <param name="Status">Pending | Snapshotting | Complete | Unavailable | ConditionCapacity.</param>
/// <param name="Observed">The last count the origin reported or listed for it (a snapshot total, or the committed set).</param>
/// <param name="Limit">The mapping's <c>MaxConditions</c>.</param>
/// <param name="Refusal">The origin's last refusal status for its item or root (null when not refused).</param>
public sealed record ConditionMappingDiagnostics(string MappingId, string Status, int Observed, int Limit, string? Refusal = null);
/// <summary>A4: consumer evidence of one connection's imported conditions (plan §6 "AdminUI").</summary>
/// <param name="StreamState">idle (no event subscriber) | connecting | snapshotting | live.</param>
/// <param name="SnapshotAtUtc">When the connection's last snapshot barrier passed (null: none since start).</param>
/// <param name="Materialised">Imported conditions this node holds for the connection.</param>
/// <param name="StateUnknown">Of those, how many carry <c>state_known = false</c> (never shown known-inactive).</param>
/// <param name="RefreshRequired">RefreshRequired requests made for the connection since start (explicit, plus each removal batch).</param>
/// <param name="Resyncs">Condition streams that ended and re-snapshotted since start.</param>
/// <param name="CapacityRejections">Mappings reset to ConditionCapacity since start.</param>
/// <param name="Mappings">Per mapping: status, observed count vs limit, refusal.</param>
/// <param name="ChargedConditions">Imported conditions charged against this node's host caps (every connection).</param>
/// <param name="HostConditionLimit">The node-wide condition cap implied by <c>MaxImportedConditionNodes</c>/<c>Bytes</c>.</param>
public sealed record ConsumerConditionDiagnostics(string StreamState, DateTime? SnapshotAtUtc, int Materialised, int StateUnknown,
long RefreshRequired, long Resyncs, long CapacityRejections, IReadOnlyList<ConditionMappingDiagnostics> Mappings,
long ChargedConditions, long HostConditionLimit, ConditionMethodCounts Methods);
/// <summary>A4: remote condition method calls by outcome class (from <c>DataWriteState</c>).</summary>
public sealed record ConditionMethodCounts(long Succeeded, long Rejected, long Failed, long Unknown);
/// <summary>A4: origin-side evidence of the root-scoped condition items this node serves to peers.</summary>
/// <param name="OpenItems">Open condition items (all peers).</param>
/// <param name="LargestListing">The largest current listing among the open items (their last snapshot's total).</param>
/// <param name="ListingLimit">That item's <c>MaxConditions</c> limit (0 when no item is open).</param>
/// <param name="LastSnapshotAtUtc">When an item last took a snapshot (null: none since start).</param>
/// <param name="Resyncs">Items re-snapshotted after a hub reader reset since start.</param>
/// <param name="CapacityRejections">Item snapshots refused as over the item's limit since start.</param>
/// <param name="UnsignalledConditions">Native conditions whose initial state was never signalled (served <c>state_known = false</c>);
/// null when the node has no condition hub.</param>
/// <param name="Methods">Remote condition method calls served, by outcome class.</param>
public sealed record OriginConditionDiagnostics(int OpenItems, int LargestListing, int ListingLimit, DateTime? LastSnapshotAtUtc,
long Resyncs, long CapacityRejections, int? UnsignalledConditions, ConditionMethodCounts Methods);
/// <summary>H4 origin-side remote-history evidence for one node (what it serves to peers over data connections).</summary>
/// <param name="Available">The node has a historian backend and can serve remote history.</param>
@@ -51,6 +51,10 @@ public sealed record DriverInstanceDiagnostics(
/// H4: remote history this node serves to data-connection peers. Null from a sender built before H4 or when the node
/// runs no data-connection services.
/// </param>
/// <param name="OriginConditions">
/// A4: root-scoped condition items this node serves to data-connection peers. Null from a sender built before A4 or when the
/// node runs no data-connection services.
/// </param>
public sealed record NodeDiagnosticsSnapshot(
NodeId NodeId,
RevisionHash? CurrentRevision,
@@ -59,4 +63,5 @@ public sealed record NodeDiagnosticsSnapshot(
bool RunningFromCache = false,
IReadOnlyList<DataConnectionDiagnosticsSnapshot>? DataConnections = null,
IReadOnlyDictionary<string, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations>? DroppedExportOperations = null,
OriginHistoryDiagnostics? OriginHistory = null);
OriginHistoryDiagnostics? OriginHistory = null,
OriginConditionDiagnostics? OriginConditions = null);
@@ -137,6 +137,14 @@ public static class DataConnectionRegistration
diagnostics.AttachProvisionalOrigin(() => probe.Serving is not null);
return diagnostics;
});
// A4: one dependency-free condition diagnostics instance shared by the origin condition items, the consumer runtime and
// the diagnostics readers (it also backs the side-labelled otopcua.dataconn.condition* metrics).
services.AddSingleton(sp =>
{
var diagnostics = new DataConnectionConditionDiagnostics();
if (sp.GetService<ConditionStateHub>() is { } hub) diagnostics.AttachUnsignalled(() => hub.Unsignalled.Values.Sum(x => x.Conditions));
return diagnostics;
});
// H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection.
services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService<ProjectedDataAccess>(),
sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
@@ -153,7 +161,8 @@ public static class DataConnectionRegistration
{
MaxImportedConditionNodes = options.MaxImportedConditionNodes,
MaxImportedConditionBytes = options.MaxImportedConditionBytes,
}, sp.GetRequiredService<ILoggerFactory>().CreateLogger<ProjectedConditionAccess>()));
}, sp.GetRequiredService<ILoggerFactory>().CreateLogger<ProjectedConditionAccess>(),
sp.GetRequiredService<DataConnectionConditionDiagnostics>()));
services.AddSingleton<IProjectedConditionAccess>(sp => sp.GetRequiredService<ProjectedConditionAccess>());
services.AddSingleton<IConfiguredProjectionDiscovery>(sp => new ConfiguredProjectionDiscovery(
sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(), sp.GetRequiredService<IFederatedProjectionCatalog>(),
@@ -197,7 +206,7 @@ public static class DataConnectionRegistration
// A2: root-scoped condition items over the A1 hub and the node manager's snapshot port.
sp.GetService<ConditionStateHub>(), new DeferredOriginConditionSource(sp.GetRequiredService<DeferredAddressSpaceSink>()),
// A2b security review: the audit trail on its OWN category from the host's logger factory.
sp.GetRequiredService<IDataConnectionAuditLog>());
sp.GetRequiredService<IDataConnectionAuditLog>(), sp.GetRequiredService<DataConnectionConditionDiagnostics>());
});
services.AddSingleton<IDataConnectionFactory>(sp => new DeferredFactory(() => sp.GetRequiredService<LocalDataRuntimeComposition>().Services));
services.AddSingleton<DataConnectionSecretChangeHandler>();
@@ -264,6 +273,7 @@ public static class DataConnectionRegistration
{
Logger = LoggerFor<DataConnectionDeploymentRuntime>(sp),
HistoryDiagnostics = sp.GetRequiredService<DataConnectionHistoryDiagnostics>(),
ConditionDiagnostics = sp.GetRequiredService<DataConnectionConditionDiagnostics>(),
};
return runtime;
});
@@ -43,7 +43,7 @@ internal sealed record ConditionItemScope(object Catalog, IReadOnlyList<ScopedCo
/// the session's pending/message limits, S5), and a record too large for it has its free text (message, comment, user)
/// truncated; one that cannot fit even so is reported through <see cref="Oversized"/>.</para>
/// </remarks>
internal sealed class ConditionItemStream : IDisposable
internal sealed class ConditionItemStream : IDisposable, DataConnectionConditionDiagnostics.IOriginItem
{
/// <summary>The most records one chunk carries.</summary>
internal const int MaxRecordsPerChunk = 128;
@@ -90,8 +90,10 @@ internal sealed class ConditionItemStream : IDisposable
/// <param name="reserveSnapshot">Charges a snapshot's estimated bytes (null = refused); default: never refused.</param>
/// <param name="chunkBytes">The most estimated record bytes one chunk carries (≤ <see cref="MaxChunkBytes"/>).</param>
internal ConditionItemStream(ConditionStateHub hub, IOriginConditionSource source, Func<ConditionItemScope> scope,
bool includeInfo, TimeProvider clock, Func<long, IDisposable?>? reserveSnapshot = null, long chunkBytes = MaxChunkBytes)
bool includeInfo, TimeProvider clock, Func<long, IDisposable?>? reserveSnapshot = null, long chunkBytes = MaxChunkBytes,
DataConnectionConditionDiagnostics? diagnostics = null)
{
Diagnostics = diagnostics;
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
_source = source ?? throw new ArgumentNullException(nameof(source));
_scope = scope ?? throw new ArgumentNullException(nameof(scope));
@@ -108,6 +110,14 @@ internal sealed class ConditionItemStream : IDisposable
/// <summary>The most estimated record bytes one chunk carries.</summary>
internal long ChunkBytes { get; }
/// <summary>A4: the node's condition diagnostics (null: metrics only).</summary>
internal DataConnectionConditionDiagnostics? Diagnostics { get; }
private long _lastSnapshotUtcTicks;
int DataConnectionConditionDiagnostics.IOriginItem.Total => Volatile.Read(ref _total);
int DataConnectionConditionDiagnostics.IOriginItem.Limit => Volatile.Read(ref _limit);
long DataConnectionConditionDiagnostics.IOriginItem.LastSnapshotTicks => Interlocked.Read(ref _lastSnapshotUtcTicks);
/// <summary>A record could not be made to fit <see cref="ChunkBytes"/>; the session ends the stream.</summary>
internal bool Oversized { get; private set; }
@@ -162,6 +172,12 @@ internal sealed class ConditionItemStream : IDisposable
lock (_leaseGate) ReleaseLease();
}
private void CountCapacityRejection()
{
if (Diagnostics is { } diagnostics) diagnostics.OriginCapacityRejection();
else DataConnectionConditionDiagnostics.CountCapacityRejection(DataConnectionConditionDiagnostics.OriginSide);
}
/// <summary>Produce the next chunk, or null when there is nothing to send now.</summary>
internal ConditionChunk? Next()
{
@@ -193,7 +209,8 @@ internal sealed class ConditionItemStream : IDisposable
private ConditionChunk? ResetSnapshot(ConditionItemScope scope)
{
Resets++;
OtOpcUaTelemetry.DataConnConditionResyncs.Add(1);
if (Diagnostics is { } diagnostics) diagnostics.OriginResync();
else DataConnectionConditionDiagnostics.CountResync(DataConnectionConditionDiagnostics.OriginSide);
_state = State.NeedSnapshot;
return CanSnapshotNow() ? TakeSnapshot(scope) : null;
}
@@ -237,6 +254,8 @@ internal sealed class ConditionItemStream : IDisposable
{
Snapshots++;
_lastSnapshotAt = _clock.GetTimestamp();
Interlocked.Exchange(ref _lastSnapshotUtcTicks, _clock.GetUtcNow().UtcTicks);
Diagnostics?.OriginSnapshot(_clock.GetUtcNow().UtcTicks);
_catalog = scope.Catalog;
_limit = scope.Limit;
lock (_leaseGate) ReleaseLease();
@@ -247,7 +266,7 @@ internal sealed class ConditionItemStream : IDisposable
{
// §5.5: total above the limit is reported at snapshot begin, before (and instead of) any record.
_state = State.OverCapacity;
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
CountCapacityRejection();
_total = listing.Count;
return new ConditionChunk(true, listing.Count, [], false);
}
@@ -261,7 +280,7 @@ internal sealed class ConditionItemStream : IDisposable
if (records.Count > _limit)
{
_state = State.OverCapacity;
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
CountCapacityRejection();
_total = records.Count;
return new ConditionChunk(true, records.Count, [], false);
}
@@ -282,7 +301,7 @@ internal sealed class ConditionItemStream : IDisposable
if (_reserveSnapshot(bytes) is not { } lease)
{
MemoryRejections++;
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
CountCapacityRejection();
_snapshotRecords.Clear(); _sliceWatermarks.Clear(); _sent.Clear();
_state = State.NeedSnapshot; // retried after MinResnapshotInterval
return null;
@@ -0,0 +1,193 @@
using System.Collections.Concurrent;
using System.Diagnostics.Metrics;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>
/// A4 imported/exported-condition diagnostics and metrics for one process (plan §6 "AdminUI" and "Metrics"), shaped like
/// H4's <see cref="DataConnectionHistoryDiagnostics"/>: dependency-free, shared by the origin services
/// (<see cref="LocalDataServices"/>, its condition items), the consumer runtime (<see cref="ProjectedConditionAccess"/>) and
/// the diagnostics readers (<see cref="DataConnectionDeploymentRuntime"/>, the driver host), so none depends on another.
/// </summary>
/// <remarks>
/// <para>Metrics, on <see cref="OtOpcUaTelemetry.Meter"/>, never carry an id in a label; every one carries <c>side</c>
/// (origin | consumer), because a node can be both (the H4 convention):</para>
/// <list type="bullet">
/// <item><c>otopcua.dataconn.conditions.items{side}</c> — open condition items: origin = root-scoped items served to peers;
/// consumer = the items its condition streams hold open (one per acked mapping).</item>
/// <item><c>otopcua.dataconn.conditions.resyncs{side}</c> — origin: an item re-snapshotted after a hub reader reset;
/// consumer: a condition stream that ended (it re-snapshots on the next).</item>
/// <item><see cref="RefreshRequiredCounterName"/><c>{side=consumer}</c> — RefreshRequired requests the consumer runtime
/// made (an incomplete barrier with a changed incomplete set, a capacity reset that removed nothing, each removal batch).</item>
/// <item><c>otopcua.dataconn.conditions.capacity_rejections{side}</c> — origin: an item snapshot over its limit; consumer: a
/// mapping reset to ConditionCapacity (over its MaxConditions or the host caps).</item>
/// <item><c>otopcua.dataconn.condition_methods{method,outcome,side}</c> — origin: calls served; consumer: calls forwarded
/// (outcome = the <c>DataWriteState</c>).</item>
/// </list>
/// </remarks>
public sealed class DataConnectionConditionDiagnostics
{
public const string OriginSide = "origin";
public const string ConsumerSide = "consumer";
public const string RefreshRequiredCounterName = "otopcua.dataconn.conditions.refresh_required";
private static readonly Counter<long> RefreshRequiredCounter = OtOpcUaTelemetry.Meter.CreateCounter<long>(RefreshRequiredCounterName,
unit: "{request}", description: "RefreshRequired requests made by the imported-condition runtime (tag side = consumer).");
private static KeyValuePair<string, object?> Side(string side) => new("side", side);
internal static void CountItems(string side, int delta) => OtOpcUaTelemetry.DataConnConditionItems.Add(delta, Side(side));
internal static void CountResync(string side) => OtOpcUaTelemetry.DataConnConditionResyncs.Add(1, Side(side));
internal static void CountCapacityRejection(string side) => OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1, Side(side));
internal static void CountMethod(string side, DataConditionMethods method, DataWriteState outcome) =>
OtOpcUaTelemetry.DataConnConditionMethods.Add(1, new KeyValuePair<string, object?>("method", method.ToString()),
new KeyValuePair<string, object?>("outcome", outcome.ToString()), Side(side));
private sealed class Methods
{
public long Succeeded, Rejected, Failed, Unknown;
public void Add(DataWriteState outcome)
{
switch (outcome)
{
case DataWriteState.DriverConfirmedSuccess: Interlocked.Increment(ref Succeeded); break;
case DataWriteState.RejectedBeforeDispatch: Interlocked.Increment(ref Rejected); break;
case DataWriteState.DriverConfirmedFailure: Interlocked.Increment(ref Failed); break;
default: Interlocked.Increment(ref Unknown); break;
}
}
public ConditionMethodCounts Capture() =>
new(Interlocked.Read(ref Succeeded), Interlocked.Read(ref Rejected), Interlocked.Read(ref Failed), Interlocked.Read(ref Unknown));
}
private sealed class ConsumerCounts
{
public long Refresh, Resyncs, Capacity;
public readonly Methods Methods = new();
}
/// <summary>What the consumer runtime reports for one connection (null: no condition-bearing mapping on it).</summary>
public sealed record ConsumerState(string StreamState, DateTime? SnapshotAtUtc, int Materialised, int StateUnknown,
ConditionMappingDiagnostics[] Mappings, long ChargedConditions, long HostConditionLimit);
/// <summary>An origin condition item's current listing (read at capture; plain ints, written by the item's producer).</summary>
internal interface IOriginItem
{
int Total { get; }
int Limit { get; }
long LastSnapshotTicks { get; }
}
private readonly ConcurrentDictionary<string, ConsumerCounts> _consumer = new(StringComparer.OrdinalIgnoreCase);
private readonly Methods _originMethods = new();
private readonly ConcurrentDictionary<IOriginItem, byte> _originItems = new(ReferenceEqualityComparer.Instance);
private long _originResyncs, _originCapacity, _originLastSnapshotTicks;
private Func<string, ConsumerState?>? _consumerState;
private Func<int>? _unsignalled;
private ConsumerCounts Consumer(string connectionId) => _consumer.GetOrAdd(connectionId, static _ => new ConsumerCounts());
// ------------------------------------------------------------------ consumer
/// <summary>Connects the consumer runtime whose live per-connection state this reports.</summary>
internal void AttachConsumer(Func<string, ConsumerState?> state) => _consumerState = state;
internal void ConsumerRefreshRequired(string connectionId)
{
Interlocked.Increment(ref Consumer(connectionId).Refresh);
RefreshRequiredCounter.Add(1, Side(ConsumerSide));
}
internal void ConsumerResync(string connectionId)
{
Interlocked.Increment(ref Consumer(connectionId).Resyncs);
CountResync(ConsumerSide);
}
internal void ConsumerCapacityRejection(string connectionId)
{
Interlocked.Increment(ref Consumer(connectionId).Capacity);
CountCapacityRejection(ConsumerSide);
}
internal void ConsumerMethod(string connectionId, DataConditionMethods method, DataWriteState outcome)
{
Consumer(connectionId).Methods.Add(outcome);
CountMethod(ConsumerSide, method, outcome);
}
/// <summary>The consumer evidence of one connection; null when it carries no condition-bearing mapping.</summary>
public ConsumerConditionDiagnostics? CaptureConsumer(string connectionId)
{
ConsumerState? state;
try { state = _consumerState?.Invoke(connectionId); }
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException) { state = null; }
if (state is null) return null;
var counts = _consumer.TryGetValue(connectionId, out var c) ? c : new ConsumerCounts();
return new ConsumerConditionDiagnostics(state.StreamState, state.SnapshotAtUtc, state.Materialised, state.StateUnknown,
Interlocked.Read(ref counts.Refresh), Interlocked.Read(ref counts.Resyncs), Interlocked.Read(ref counts.Capacity), state.Mappings,
state.ChargedConditions, state.HostConditionLimit, counts.Methods.Capture());
}
// ------------------------------------------------------------------ origin
/// <summary>Connects the condition hub's unsignalled count (state_known = false at the origin).</summary>
public void AttachUnsignalled(Func<int> unsignalled) => _unsignalled = unsignalled;
internal void OriginItemOpened(IOriginItem item)
{
_originItems.TryAdd(item, 0);
CountItems(OriginSide, 1);
}
internal void OriginItemClosed(IOriginItem item)
{
if (_originItems.TryRemove(item, out _)) CountItems(OriginSide, -1);
}
internal void OriginSnapshot(long utcTicks) => Interlocked.Exchange(ref _originLastSnapshotTicks, utcTicks);
internal void OriginResync()
{
Interlocked.Increment(ref _originResyncs);
CountResync(OriginSide);
}
internal void OriginCapacityRejection()
{
Interlocked.Increment(ref _originCapacity);
CountCapacityRejection(OriginSide);
}
internal void OriginMethod(DataConditionMethods method, DataWriteState outcome)
{
_originMethods.Add(outcome);
CountMethod(OriginSide, method, outcome);
}
/// <summary>The origin evidence of this node (never null from an A4 build; zeros before any peer).</summary>
public OriginConditionDiagnostics CaptureOrigin()
{
int largest = 0, limit = 0;
foreach (var item in _originItems.Keys)
{
var total = item.Total;
// The item nearest its limit is the one to show (largest ratio; ties → largest listing).
if (limit == 0 || (long)total * Math.Max(1, limit) > (long)largest * Math.Max(1, item.Limit)) { largest = total; limit = item.Limit; }
}
int? unsignalled;
try { unsignalled = _unsignalled?.Invoke(); }
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException) { unsignalled = null; }
var ticks = Interlocked.Read(ref _originLastSnapshotTicks);
return new OriginConditionDiagnostics(_originItems.Count, largest, limit, ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc),
Interlocked.Read(ref _originResyncs), Interlocked.Read(ref _originCapacity), unsignalled, _originMethods.Capture());
}
}
@@ -48,6 +48,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
public ILogger Logger { private get; init; } = NullLogger.Instance;
/// <summary>H4: consumer/origin remote-history evidence merged into the diagnostics; optional (init keeps the constructor shape).</summary>
public DataConnectionHistoryDiagnostics? HistoryDiagnostics { get; init; }
/// <summary>A4: consumer/origin imported-condition evidence merged into the diagnostics; optional (init keeps the constructor shape).</summary>
public DataConnectionConditionDiagnostics? ConditionDiagnostics { get; init; }
private IReadOnlyDictionary<string, DataOperations> _droppedOperations = new Dictionary<string, DataOperations>();
private long _unknownOperationRows;
private readonly string _node, _owner;
@@ -121,9 +123,11 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
int? MappingDrops(string id) => mappingsWithDroppedOperations is null ? null
: mappingsWithDroppedOperations.TryGetValue(id, out var count) ? count : 0;
var history = HistoryDiagnostics;
var conditions = ConditionDiagnostics;
ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot WithHistory(
ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot row)
{
if (conditions is not null) row = row with { Conditions = conditions.CaptureConsumer(row.ConnectionId) };
if (history is null) return row;
var counts = history.CaptureConsumer(row.ConnectionId);
return row with { HistoryReadsGood = counts.Good, HistoryReadsUncertain = counts.Uncertain, HistoryReadsBad = counts.Bad,
@@ -35,7 +35,8 @@ internal sealed partial class DataSubscriptionSession
{
Stream.Dispose(); // releases the snapshot memory charge
r.Dispose();
OtOpcUaTelemetry.DataConnConditionItems.Add(-1);
if (Stream.Diagnostics is { } diagnostics) diagnostics.OriginItemClosed(Stream);
else DataConnectionConditionDiagnostics.CountItems(DataConnectionConditionDiagnostics.OriginSide, -1);
}
}
}
@@ -108,9 +109,11 @@ internal sealed partial class DataSubscriptionSession
var principal = _context.PrincipalId;
var snapshots = _capacity.Snapshots;
var stream = new ConditionItemStream(hub, source, authority.Scope, request.ConditionScope!.IncludeInfo, services.Clock,
reserveSnapshot: bytes => snapshots.TryAcquire(principal, bytes, out var lease) ? lease : null, chunkBytes: chunkBytes);
reserveSnapshot: bytes => snapshots.TryAcquire(principal, bytes, out var lease) ? lease : null, chunkBytes: chunkBytes,
diagnostics: services.ConditionDiagnostics);
var item = new ConditionItem(request.ClientItemId, handle, authority, stream, reservation!);
OtOpcUaTelemetry.DataConnConditionItems.Add(1);
if (stream.Diagnostics is { } itemDiagnostics) itemDiagnostics.OriginItemOpened(stream);
else DataConnectionConditionDiagnostics.CountItems(DataConnectionConditionDiagnostics.OriginSide, 1);
lock (_gate)
{
_conditionItems.Add(handle.Handle, item);
@@ -25,7 +25,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable
ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null,
DataConnectionHistoryDiagnostics? historyDiagnostics = null,
ConditionStateHub? conditionHub = null, ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginConditionSource? conditionSource = null,
IDataConnectionAuditLog? audit = null)
IDataConnectionAuditLog? audit = null, DataConnectionConditionDiagnostics? conditionDiagnostics = null)
{
ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub);
ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities);
@@ -49,6 +49,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable
Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, HistoryDiagnostics = historyDiagnostics,
// A2: condition streams over the A1 hub and the node manager's snapshot port; keys from the coordinator.
ConditionHub = conditionHub, ConditionSource = conditionSource, ConditionKeysSource = () => catalog.ConditionKeys,
ConditionDiagnostics = conditionDiagnostics,
// A2b security review: the audit trail on its own logger category (the Host passes it), never the services' logger.
Audit = audit ?? new LoggerDataConnectionAuditLog(logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance),
ConditionMethodMaxOperations = limits.MaxConditionMethodOperations,
@@ -161,8 +161,8 @@ public sealed partial class LocalDataServices
{
Logger.LogError(ex, "The data-connection audit log failed to record a condition method call");
}
OtOpcUaTelemetry.DataConnConditionMethods.Add(1, new KeyValuePair<string, object?>("method", request.Method.ToString()),
new KeyValuePair<string, object?>("outcome", state.ToString()));
if (ConditionDiagnostics is { } diagnostics) diagnostics.OriginMethod(request.Method, state);
else DataConnectionConditionDiagnostics.CountMethod(DataConnectionConditionDiagnostics.OriginSide, request.Method, state);
}
async Task<(DataConditionMethodResult, bool)> DecideAsync()
@@ -20,6 +20,9 @@ public sealed partial class LocalDataServices
/// <summary>A1/A2: the condition-state hub the node manager feeds (null ⇒ conditions are not servable).</summary>
public ConditionStateHub? ConditionHub { get; init; }
/// <summary>A4: the node's condition diagnostics (items, snapshots, resyncs, capacity, method outcomes); null = metrics only.</summary>
public DataConnectionConditionDiagnostics? ConditionDiagnostics { get; init; }
/// <summary>A2: the node manager's condition snapshot port (null ⇒ conditions are not servable).</summary>
public IOriginConditionSource? ConditionSource { get; init; }
@@ -52,8 +52,20 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod
public async Task<DataConditionMethodResult> CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(call);
ServingIdentity? serving;
lock (_gate) serving = _runners.TryGetValue(call.ConnectionId, out var runner) ? runner.Serving : null;
var outcome = DataWriteState.OutcomeUnknown;
try
{
var result = await ForwardAsync(call, cancellationToken).ConfigureAwait(false);
outcome = result.State;
return result;
}
finally { Diagnostics.ConsumerMethod(call.ConnectionId, call.Method, outcome); } // A4: every forwarded call, by outcome
}
private async Task<DataConditionMethodResult> ForwardAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken)
{
// #931 N6: no _gate here — a method call must never queue behind a runner stop (which takes the stale gate).
var serving = _runners.TryGetValue(call.ConnectionId, out var runner) ? runner.Serving : null;
// No open condition stream ⇒ no serving incarnation to address: the connection is down for this purpose. Nothing sent.
if (serving is null)
return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "No condition stream is open on the connection.");
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
@@ -24,8 +25,24 @@ public sealed partial class ProjectedConditionAccess
private sealed class Entry
{
public int Materialised;
/// <summary>#931 N5: materialised keys no contributing mapping lists (an Unavailable mapping's stale-held keys).</summary>
public int Unlisted;
public readonly Dictionary<string, int> Claims = new(StringComparer.OrdinalIgnoreCase);
public long Charge => Math.Max(Materialised, Claims.Values.Sum(x => (long)x));
/// <summary>Claims of mappings with no committed set in this stream (first snapshot / retry): they may re-list the
/// held-but-unlisted keys, so they overlap <see cref="Unlisted"/> instead of adding to it.</summary>
public readonly HashSet<string> Unknown = new(StringComparer.OrdinalIgnoreCase);
// N5: max(Materialised, ΣClaims) under-counted while one mapping's stale keys were held and another (known) mapping
// claimed new ones. The held-but-unlisted keys are charged beside the known mappings' claims; an unknown mapping's
// claim may be those very keys, so it is charged as max(Unlisted, Σ unknown claims).
public long Charge
{
get
{
long known = 0, unknown = 0;
foreach (var (mapping, count) in Claims) if (Unknown.Contains(mapping)) unknown += count; else known += count;
return Math.Max(Materialised, known + Math.Max(Unlisted, unknown));
}
}
}
private readonly object _gate = new();
@@ -43,39 +60,65 @@ public sealed partial class ProjectedConditionAccess
conditions * ProjectedConditionOptions.NodesPerCondition > options.MaxImportedConditionNodes * 8L / 10;
/// <summary>Sets a mapping's claim when the node total stays within both caps; otherwise leaves it unchanged.</summary>
public bool TryClaim(string connection, string mapping, int count, out long total)
/// <param name="unknown">The mapping has no committed set in this stream yet (N5: its claim may overlap held keys).</param>
public bool TryClaim(string connection, string mapping, int count, bool unknown, out long total)
{
lock (_gate)
{
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
var had = entry.Claims.TryGetValue(mapping, out var previous);
var wasUnknown = entry.Unknown.Contains(mapping);
entry.Claims[mapping] = count;
if (unknown) entry.Unknown.Add(mapping); else entry.Unknown.Remove(mapping);
total = TotalLocked();
if (!Over(total) || count <= previous) return true;
if (!Over(total) || (count <= previous && unknown == wasUnknown)) return true;
if (had) entry.Claims[mapping] = previous; else entry.Claims.Remove(mapping);
if (wasUnknown) entry.Unknown.Add(mapping); else entry.Unknown.Remove(mapping);
return false;
}
}
/// <summary>The swap: the mapping's committed count (≤ its admitted total), now a known claim. Never refused.</summary>
public void Commit(string connection, string mapping, int count)
{
lock (_gate)
{
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
entry.Claims[mapping] = count;
entry.Unknown.Remove(mapping);
}
}
public void Release(string connection, string mapping)
{
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Remove(mapping);
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) { entry.Claims.Remove(mapping); entry.Unknown.Remove(mapping); }
}
public void ResetClaims(string connection)
{
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Clear();
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) { entry.Claims.Clear(); entry.Unknown.Clear(); }
}
public void SetMaterialised(string connection, int count)
/// <summary>
/// Records what a connection holds. #931 N5: returns false when the node total is now over a host cap — materialising
/// is never refused here (the keys were admitted by their claims; growth is bounded by Σ MaxConditions), so the caller
/// only reports it.
/// </summary>
public bool SetMaterialised(string connection, int count, int unlisted = 0)
{
lock (_gate)
{
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
entry.Materialised = count;
if (count == 0 && entry.Claims.Count == 0) _connections.Remove(connection);
entry.Unlisted = Math.Min(unlisted, count);
if (count == 0 && entry.Claims.Count == 0) { _connections.Remove(connection); return true; }
return !Over(TotalLocked());
}
}
/// <summary>The node-wide condition cap implied by the node and byte caps (for diagnostics).</summary>
public long ConditionLimit => Math.Min(options.MaxImportedConditionNodes / ProjectedConditionOptions.NodesPerCondition,
options.MaxImportedConditionBytes / ProjectedConditionOptions.BytesPerCondition);
}
// -----------------------------------------------------------------------------------------------------------------
@@ -124,8 +167,23 @@ public sealed partial class ProjectedConditionAccess
public ulong? Handle { get; set; }
public DataItemHandle? ItemHandle { get; set; }
public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending;
/// <summary>The origin refused the item (or its metadata failed): nothing more arrives on this stream.</summary>
/// <summary>The origin refused the item (or its metadata failed): nothing more arrives for it until an in-stream retry.</summary>
public bool Refused { get; set; }
/// <summary>#930: the status of the last refusal (item ack or root metadata); null when not refused.</summary>
public DataItemStatus? Refusal { get; set; } // written under _statusGate (MarkRefused / retry), read there by Capture
/// <summary>#930: the command whose ack belongs to the mapping's current item ("open", then "retry-…").</summary>
public string CommandId { get; set; } = "open";
/// <summary>#930: when the next in-stream retry (or, while <see cref="Retrying"/>, the retry's snapshot deadline) is due.</summary>
public DateTimeOffset? RetryDue { get; set; }
/// <summary>#930: a re-added item awaits its ack / snapshot.</summary>
public bool Retrying { get; set; }
/// <summary>#930: consecutive in-stream retries (reset by a completed snapshot); drives the backoff.</summary>
public int Retries { get; set; }
/// <summary>A4 diagnostics: the last count the origin reported or listed (a snapshot total, or the committed set).</summary>
public int ObservedField;
public int Observed { get => Volatile.Read(ref ObservedField); set => Volatile.Write(ref ObservedField, value); }
/// <summary>A4: the consumer <c>conditions.items</c> gauge counts this mapping's open item.</summary>
public bool ItemCounted { get; set; }
/// <summary>The mapping's committed complete set in this stream (null until its first snapshot completes).</summary>
public ConditionSet? Live { get; set; }
/// <summary>Review r1 B1: a (re-)snapshot in progress, swapped in only at <c>snapshot_complete</c>.</summary>
@@ -153,7 +211,17 @@ public sealed partial class ProjectedConditionAccess
private ITimer? _stale;
private long _staleGeneration;
private int _barriers;
private int _consecutiveRetries;
/// <summary>#931 N4: consecutive streams that ended before their barrier (reconnect backoff).</summary>
private int _failedStreams;
/// <summary>#930 N2: the mappings that were not known at the last barrier (null before the first); an incomplete barrier
/// with the SAME set sends no RefreshRequired — the clients were already told.</summary>
private HashSet<string>? _lastIncomplete;
/// <summary>A4 diagnostics: materialised keys whose last record had <c>state_known = false</c>.</summary>
private readonly HashSet<string> _unknownKeys = new(StringComparer.Ordinal);
private int _unknownCount;
private long _snapshotAtTicks;
private int _streamOpen;
private int _unlisted;
public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature,
ConnectionRunner? predecessor)
@@ -168,6 +236,29 @@ public sealed partial class ProjectedConditionAccess
/// <summary>A3b: the serving identity of the CURRENT condition stream (null while no stream is open).</summary>
public ServingIdentity? Serving => Volatile.Read(ref _serving);
/// <summary>A4 diagnostics (any thread): stream state, last barrier time, materialised / state-unknown counts, mappings.</summary>
public (string State, DateTime? SnapshotAt, int Materialised, int Unknown, ConditionMappingDiagnostics[] Mappings) Capture()
{
MappingState[] states;
ConditionMappingDiagnostics[] rows;
lock (_statusGate)
{
states = _states;
rows = states.Select(x => new ConditionMappingDiagnostics(x.MappingId, x.Status.ToString(), Volatile.Read(ref x.ObservedField),
x.Placement.Mapping.MaxConditions, x.Refusal?.ToString())).ToArray();
}
var state = Volatile.Read(ref _streamOpen) == 0 ? "connecting"
: states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting) && !BarrierThisStream
? "snapshotting" : "live";
var ticks = Interlocked.Read(ref _snapshotAtTicks);
return (state, ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc), Volatile.Read(ref _materialisedCount),
Volatile.Read(ref _unknownCount), rows);
}
private volatile bool _barrierThisStream;
private bool BarrierThisStream => _barrierThisStream;
private int _materialisedCount;
/// <summary>Completes once the loop ended and (for a removing stop) its conditions were removed.</summary>
public Task Stopped => _stopped;
@@ -196,6 +287,11 @@ public sealed partial class ProjectedConditionAccess
try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); }
_materialised = previous._materialised;
previous._materialised = new HashSet<string>(StringComparer.Ordinal);
_unknownKeys.UnionWith(previous._unknownKeys);
_unknownKeys.IntersectWith(_materialised);
previous._unknownKeys.Clear();
Volatile.Write(ref _materialisedCount, _materialised.Count);
Volatile.Write(ref _unknownCount, _unknownKeys.Count);
_predecessor = null;
}
@@ -212,6 +308,9 @@ public sealed partial class ProjectedConditionAccess
var keys = _materialised.ToArray();
if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys);
_materialised.Clear();
_unknownKeys.Clear();
Volatile.Write(ref _materialisedCount, 0);
Volatile.Write(ref _unknownCount, 0);
_owner._ledger.ResetClaims(ConnectionId);
_owner._ledger.SetMaterialised(ConnectionId, 0);
}, TaskScheduler.Default);
@@ -223,21 +322,34 @@ public sealed partial class ProjectedConditionAccess
while (!ct.IsCancellationRequested)
{
epoch++;
var barriers = Barriers;
try { await RunStreamAsync(epoch, ct).ConfigureAwait(false); }
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
catch (Exception ex)
{
_owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", ConnectionId);
if (_failedStreams == 0) _owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", ConnectionId);
else _owner._log.LogDebug(ex, "Imported conditions: stream for connection {Connection} ended again ({Failures} in a row)", ConnectionId, _failedStreams + 1);
}
finally { Volatile.Write(ref _serving, null); }
finally { Volatile.Write(ref _serving, null); Volatile.Write(ref _streamOpen, 0); }
// §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead.
ArmStale();
OtOpcUaTelemetry.DataConnConditionResyncs.Add(1);
try { await Task.Delay(_owner._options.ReconnectDelay, _owner._clock, ct).ConfigureAwait(false); }
_owner.Diagnostics.ConsumerResync(ConnectionId);
// #931 N4: a stream that never reached its barrier (metadata failing for every mapping, no Primary during a
// failover) backs off exponentially up to MaxReconnectDelay instead of looping at ReconnectDelay.
_failedStreams = Barriers > barriers ? 0 : _failedStreams + 1;
try { await Task.Delay(ReconnectBackoff(_owner._options, _failedStreams), _owner._clock, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
}
}
/// <summary>#931 N4: ReconnectDelay × 2^(failures − 1), capped at MaxReconnectDelay (never below ReconnectDelay).</summary>
internal static TimeSpan ReconnectBackoff(ProjectedConditionOptions options, int failures)
{
if (failures <= 1) return options.ReconnectDelay;
var ticks = options.ReconnectDelay.Ticks * (double)(1L << Math.Min(failures - 1, 20));
return TimeSpan.FromTicks((long)Math.Max(options.ReconnectDelay.Ticks, Math.Min(ticks, options.MaxReconnectDelay.Ticks)));
}
private void ArmStale()
{
lock (_staleGate)
@@ -273,29 +385,7 @@ public sealed partial class ProjectedConditionAccess
// The remote root's origin subject: placement addresses are made relative to it (SourceName, folder subject).
// S6: a root whose metadata fails is Unavailable (its item is not opened — a root item without the origin's own
// view is refused, and placements made relative to a missing root subject would be wrong).
try
{
var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, states.Length), 1024 * 1024);
var metadata = await connection.GetMetadataAsync(new MetadataRequest(states.Select(x => x.Root).ToArray(), budget), token)
.ConfigureAwait(false);
for (var i = 0; i < states.Length; i++)
{
if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root })
{
states[i].RootSubject = root.View.Subject;
states[i].RootView = root.View;
continue;
}
MarkRefused(states[i]);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried on a new stream",
states[i].MappingId, i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
foreach (var state in states) MarkRefused(state);
_owner._log.LogWarning(ex, "Imported conditions: connection {Connection} root metadata failed — every mapping Unavailable", ConnectionId);
}
await ResolveRootsAsync(connection, states, token).ConfigureAwait(false);
var open = states.Where(x => !x.Refused).ToArray();
if (open.Length == 0) throw new InvalidOperationException("No condition-bearing mapping root resolved.");
@@ -307,24 +397,25 @@ public sealed partial class ProjectedConditionAccess
if (serving is not null && !string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"Condition stream served by a {serving.Role} ({serving.NodeId}); conditions are pinned to the Primary.");
Volatile.Write(ref _serving, serving);
_barrierThisStream = false;
Volatile.Write(ref _streamOpen, 1);
_owner._log.LogInformation("Imported conditions: stream {Epoch} for connection {Connection} opened ({Mappings} mapping(s), serving {Serving})",
epoch, ConnectionId, open.Length, Serving?.NodeId ?? "(no provenance)");
var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N");
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
var items = open.Select(x => new DataSubscriptionItem(x.MappingId, x.RootView ?? x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray();
await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false,
TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false);
var items = open.Select(Item).ToArray();
var snapshotTimeout = TimeSpan.FromMilliseconds(Math.Max(1, states.Max(x => x.Placement.Mapping.ConditionSnapshotTimeoutMilliseconds)));
var barrierPassed = false;
var timeout = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var barrierTimer = _owner._clock.CreateTimer(_ => timeout.TrySetResult(), null, snapshotTimeout, Timeout.InfiniteTimeSpan);
// B2: a mapping still Unavailable a bounded wait after the barrier ends the stream (a fresh stream retries it).
// #930: one timer for the earliest in-stream retry due (re-armed when that changes); its signal is a fresh TCS.
var retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
ITimer? retryTimer = null;
DateTimeOffset? retryArmedFor = null;
var context = new StreamContext(subscription, subscriptionId, epoch, token);
try
{
await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false,
TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false);
using var barrierTimer = _owner._clock.CreateTimer(_ => timeout.TrySetResult(), null, snapshotTimeout, Timeout.InfiniteTimeSpan);
await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token);
Task<bool>? next = null;
while (true)
@@ -340,24 +431,32 @@ public sealed partial class ProjectedConditionAccess
}
if (barrierPassed)
{
var unavailable = states.Any(x => x.Status == ProjectedConditionMappingStatus.Unavailable);
if (retry.Task.IsCompleted && unavailable)
// #930 (N2/N3): an Unavailable or over-capacity mapping is retried ON THIS STREAM (its item re-added) on
// its own backoff — the stream is no longer ended for it, so the healthy mappings are not re-snapshotted
// and clients are not sent RefreshRequired every cycle.
if (retry.Task.IsCompleted)
{
_consecutiveRetries++;
_owner._log.LogWarning("Imported conditions: connection {Connection} mapping(s) {Mappings} still Unavailable — ending the stream to retry",
ConnectionId, string.Join(", ", states.Where(x => x.Status == ProjectedConditionMappingStatus.Unavailable).Select(x => x.MappingId)));
return;
retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
retryArmedFor = null;
await RetryDueAsync(connection, states, context, snapshotTimeout).ConfigureAwait(false);
}
if (!unavailable)
foreach (var s in states)
if (s.RetryDue is null && s.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity)
ScheduleRetry(s, snapshotTimeout);
var due = states.Where(x => x.RetryDue is not null).Select(x => x.RetryDue!.Value).DefaultIfEmpty().Min();
DateTimeOffset? wanted = states.Any(x => x.RetryDue is not null) ? due : null;
if (wanted != retryArmedFor)
{
retryTimer?.Dispose(); retryTimer = null; _consecutiveRetries = 0;
retryTimer?.Dispose(); retryTimer = null;
if (retry.Task.IsCompleted) retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
else if (retryTimer is null)
{
var wait = snapshotTimeout * Math.Min(1 << Math.Min(_consecutiveRetries, 3), 8);
var signal = retry;
retryTimer = _owner._clock.CreateTimer(_ => signal.TrySetResult(), null, wait, Timeout.InfiniteTimeSpan);
retryArmedFor = wanted;
if (wanted is { } at)
{
var signal = retry;
var wait = at - _owner._clock.GetUtcNow();
retryTimer = _owner._clock.CreateTimer(_ => signal.TrySetResult(), null, wait > TimeSpan.Zero ? wait : TimeSpan.Zero,
Timeout.InfiniteTimeSpan);
}
}
}
next ??= frames.MoveNextAsync().AsTask();
@@ -370,24 +469,155 @@ public sealed partial class ProjectedConditionAccess
next = null;
var outcome = await ProcessAsync(frames.Current, states, context).ConfigureAwait(false);
if (!barrierPassed) { barrierPassed = TryPassBarrier(states, timedOut: false); continue; }
if (outcome.Changed.Count > 0 || outcome.Reconcile) Reconcile(states, outcome.Changed, outcome.Reconcile);
if (outcome.Refresh) _owner._sink()?.RequireRefresh(ConnectionId);
var removed = 0;
if (outcome.Changed.Count > 0 || outcome.Reconcile) removed = Reconcile(states, outcome.Changed, outcome.Reconcile);
// #931 N7: a removal already sent RefreshRequired to every item that held a removed condition (the sink's
// §5.2 "removal + RefreshRequired"); a capacity reset asks again only when it removed nothing.
if (outcome.Refresh && removed == 0) RequireRefresh();
}
}
finally { retryTimer?.Dispose(); }
finally
{
retryTimer?.Dispose();
foreach (var s in states) CountItem(s, open: false);
}
}
private static DataSubscriptionItem Item(MappingState state) =>
new(state.MappingId, state.RootView ?? state.Root, new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null),
new DataConditionScope(IncludeInfo: true));
/// <summary>Resolves the roots of <paramref name="targets"/> (metadata); a root that fails is refused (Unavailable).</summary>
private async Task ResolveRootsAsync(IDataConnection connection, MappingState[] targets, CancellationToken token)
{
if (targets.Length == 0) return;
try
{
var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, targets.Length), 1024 * 1024);
var metadata = await connection.GetMetadataAsync(new MetadataRequest(targets.Select(x => x.Root).ToArray(), budget), token)
.ConfigureAwait(false);
for (var i = 0; i < targets.Length; i++)
{
if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root })
{
targets[i].RootSubject = root.View.Subject;
targets[i].RootView = root.View;
continue;
}
var status = i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable;
MarkRefused(targets[i], status);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried in-stream",
targets[i].MappingId, status);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
foreach (var state in targets) MarkRefused(state, DataItemStatus.Unavailable);
_owner._log.LogWarning(ex, "Imported conditions: connection {Connection} root metadata failed — {Count} mapping(s) Unavailable",
ConnectionId, targets.Length);
}
}
/// <summary>#930: whether a refusal is definitive (the origin will keep saying no until its configuration changes).</summary>
private static bool Definitive(MappingState state) =>
state.Status == ProjectedConditionMappingStatus.ConditionCapacity
|| state.Refusal is DataItemStatus.Denied or DataItemStatus.NotFound or DataItemStatus.Unsupported;
/// <summary>#930: when the mapping's next in-stream retry is due — long (and doubling ≤ 4×) for a definitive refusal or
/// ConditionCapacity, the snapshot timeout × 2ⁿ (≤ 8×) otherwise.</summary>
private void ScheduleRetry(MappingState state, TimeSpan snapshotTimeout)
{
var delay = Definitive(state)
? _owner._options.LongRetryDelay * (1 << Math.Min(state.Retries, 2))
: snapshotTimeout * (1 << Math.Min(state.Retries, 3));
state.RetryDue = _owner._clock.GetUtcNow() + delay;
}
/// <summary>
/// #930: runs the in-stream retries that are due. A retry whose snapshot has not completed by its deadline becomes
/// Unavailable again (its claim released; a late completion of that item is still taken). A due Unavailable or
/// ConditionCapacity mapping has its root re-resolved when it never resolved, any still-open item removed, and its item
/// re-added with a fresh command id. While a retry runs the mapping is Pending — unknown, so nothing it might list is
/// removed or marked known-inactive meanwhile (§5.1 T2).
/// </summary>
private async Task RetryDueAsync(IDataConnection connection, MappingState[] states, StreamContext context, TimeSpan snapshotTimeout)
{
var now = _owner._clock.GetUtcNow();
var due = new List<MappingState>();
foreach (var state in states.Where(x => x.RetryDue is { } at && at <= now))
{
state.RetryDue = null;
if (state.Retrying)
{
state.Retrying = false;
if (state.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)
{
lock (_statusGate) state.Status = ProjectedConditionMappingStatus.Unavailable;
state.Buffer = null;
_owner._ledger.Release(ConnectionId, state.MappingId);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} retry snapshot timed out — Unavailable", state.MappingId);
}
continue;
}
if (state.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity) due.Add(state);
}
if (due.Count == 0) return;
foreach (var state in due) state.Retries++;
await ResolveRootsAsync(connection, due.Where(x => x.RootView is null).ToArray(), context.Token).ConfigureAwait(false);
var ready = due.Where(x => x.RootView is not null).ToArray();
// An Unavailable mapping whose snapshot timed out still has its item open: remove it before re-adding (one per root).
var stillOpen = ready.Where(x => x.ItemHandle is not null).ToArray();
foreach (var state in stillOpen) CountItem(state, open: false);
if (stillOpen.Length > 0)
await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-retry-" + Guid.NewGuid().ToString("N"),
TimeSpan.FromSeconds(30), stillOpen.Select(x => x.ItemHandle!).ToArray()), context.Token).ConfigureAwait(false);
foreach (var state in ready)
{
lock (_statusGate)
{
state.Status = ProjectedConditionMappingStatus.Pending;
state.Refused = false; state.Refusal = null;
state.Handle = null; state.ItemHandle = null;
state.CommandId = "retry-" + state.MappingId + "-" + Guid.NewGuid().ToString("N");
}
state.Buffer = null;
state.Retrying = true;
state.RetryDue = _owner._clock.GetUtcNow() + snapshotTimeout;
_owner._log.LogInformation("Imported conditions: connection {Connection} mapping {Mapping} retried in-stream (attempt {Attempt})",
ConnectionId, state.MappingId, state.Retries);
await context.Subscription.SendAsync(new AddSubscriptionItems(context.SubscriptionId, context.Epoch, state.CommandId,
TimeSpan.FromSeconds(30), [Item(state)]), context.Token).ConfigureAwait(false);
}
}
private void CountItem(MappingState state, bool open)
{
if (state.ItemCounted == open) return;
state.ItemCounted = open;
DataConnectionConditionDiagnostics.CountItems(DataConnectionConditionDiagnostics.ConsumerSide, open ? 1 : -1);
}
private void RequireRefresh()
{
_owner.Diagnostics.ConsumerRefreshRequired(ConnectionId);
_owner._sink()?.RequireRefresh(ConnectionId);
}
private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token);
private sealed record FrameOutcome(HashSet<string> Changed, bool Reconcile, bool Refresh);
private void MarkRefused(MappingState state)
private void MarkRefused(MappingState state, DataItemStatus status)
{
lock (_statusGate)
{
state.Refused = true;
state.Refusal = status;
if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable;
}
state.Retrying = false;
state.RetryDue = null; // re-scheduled (with its backoff) once past the barrier
CountItem(state, open: false);
}
private bool TryPassBarrier(MappingState[] states, bool timedOut)
@@ -395,14 +625,24 @@ public sealed partial class ProjectedConditionAccess
lock (_statusGate)
if (states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) return false;
Interlocked.Increment(ref _barriers);
Interlocked.Exchange(ref _snapshotAtTicks, _owner._clock.GetUtcNow().UtcTicks);
_barrierThisStream = true;
DisarmStale();
var incomplete = states.Any(x => !x.Known);
var incompleteSet = states.Where(x => !x.Known).Select(x => x.MappingId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var incomplete = incompleteSet.Count > 0;
// #930 N2: the same incomplete set as the last barrier ⇒ the clients were already told; a permanently refused
// mapping must not send RefreshRequired on every stream (it is retried in-stream now, but a stream can still end).
var alreadyTold = _lastIncomplete is { } last && last.SetEquals(incompleteSet);
_lastIncomplete = incompleteSet;
_owner._log.LogInformation("Imported conditions: connection {Connection} snapshot barrier passed ({Statuses}; {Records} record(s){TimedOut})",
ConnectionId, string.Join(", ", states.Select(x => x.MappingId + "=" + x.Status)), states.Where(x => x.Contributes).Sum(x => x.Live!.Records.Count),
timedOut ? "; snapshot timed out" : "");
Reconcile(states, states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal), full: true);
// S7: an incomplete (re)snapshot — a timeout OR a refused item — tells clients to refresh.
if (incomplete) _owner._sink()?.RequireRefresh(ConnectionId);
if (incomplete && !alreadyTold) RequireRefresh();
else if (incomplete)
_owner._log.LogDebug("Imported conditions: connection {Connection} incomplete set unchanged ({Mappings}) — no RefreshRequired",
ConnectionId, string.Join(", ", incompleteSet));
return true;
}
@@ -416,14 +656,16 @@ public sealed partial class ProjectedConditionAccess
case DataSubscriptionAck ack:
foreach (var itemAck in ack.Items)
{
var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId);
// #930: an ack belongs to the mapping's CURRENT command (the open, or its latest in-stream retry).
var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId && x.CommandId == ack.CommandId);
if (state is null) continue;
if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle)
{
lock (_statusGate) { state.Handle = handle.Handle; state.ItemHandle = handle; }
CountItem(state, open: true);
continue;
}
MarkRefused(state);
MarkRefused(state, itemAck.Status);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} item refused by the origin ({Status}: {Diagnostic})",
state.MappingId, itemAck.Status, itemAck.Diagnostic);
}
@@ -436,13 +678,15 @@ public sealed partial class ProjectedConditionAccess
{
// A snapshot begin: decided before anything of it is materialised; buffered until snapshot_complete (B1),
// so the committed set (and what is materialised) is untouched while it streams.
if (total > limit || !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, Math.Max(total, mapping.Live?.Records.Count ?? 0), out var after))
if (total > limit || !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, Math.Max(total, mapping.Live?.Records.Count ?? 0),
mapping.Live is null, out var after))
{
await ResetToCapacityAsync(mapping, total, total > limit ? "over its MaxConditions" : "would cross the host condition caps",
changed, context).ConfigureAwait(false);
reconcile = refresh = true;
break;
}
mapping.Observed = total;
if (_owner._ledger.HighWater(after))
_owner._log.LogWarning("Imported conditions: host condition budget above 80% ({Count} conditions)", after);
mapping.Buffer = new ConditionSet(total);
@@ -464,7 +708,7 @@ public sealed partial class ProjectedConditionAccess
string? over = null;
if (mapping.Buffer is { } buffer && buffer.Records.Count > Math.Min(buffer.Total, limit)) over = "listed more records than its snapshot total";
else if (mapping.Live is { } grown && grown.Records.Count > limit) over = "grew past its MaxConditions";
else if (mapping.Live is not null && !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, mapping.Claim, out _)) over = "grew past the host condition caps";
else if (mapping.Live is not null && !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, mapping.Claim, false, out _)) over = "grew past the host condition caps";
if (over is not null)
{
await ResetToCapacityAsync(mapping, mapping.Claim, over, changed, context).ConfigureAwait(false);
@@ -480,7 +724,11 @@ public sealed partial class ProjectedConditionAccess
mapping.Live = done;
mapping.Buffer = null;
lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete;
_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, done.Records.Count, out _); // ≤ the admitted total
_owner._ledger.Commit(ConnectionId, mapping.MappingId, done.Records.Count); // ≤ the admitted total
// #930: a completed (re)snapshot ends any retry; the mapping is known again.
mapping.Retrying = false; mapping.Retries = 0; mapping.RetryDue = null; mapping.Refusal = null;
mapping.Observed = done.Records.Count;
_lastIncomplete?.Remove(mapping.MappingId);
reconcile = true;
}
break;
@@ -495,14 +743,22 @@ public sealed partial class ProjectedConditionAccess
if (mapping.Live is { } live) changed.UnionWith(live.Records.Keys);
mapping.Live = null;
mapping.Buffer = null;
mapping.Observed = observed;
// #930 N3: re-added in-stream on the long timer (ConditionCapacity is definitive), not left empty until the stream ends.
mapping.Retrying = false;
mapping.RetryDue = null;
_owner._ledger.Release(ConnectionId, mapping.MappingId);
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
_owner.Diagnostics.ConsumerCapacityRejection(ConnectionId);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} ({Count} conditions) {Reason} (MaxConditions {Max}) — Unavailable(ConditionCapacity)",
mapping.MappingId, observed, reason, mapping.Placement.Mapping.MaxConditions);
// §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing).
if (mapping.ItemHandle is { } handle)
{
lock (_statusGate) { mapping.Handle = null; mapping.ItemHandle = null; }
CountItem(mapping, open: false);
await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-" + mapping.MappingId,
TimeSpan.FromSeconds(30), [handle]), context.Token).ConfigureAwait(false);
}
}
/// <summary>
@@ -511,12 +767,14 @@ public sealed partial class ProjectedConditionAccess
/// A key no contributing mapping lists is removed only when every mapping's set is known; while any is unknown
/// (Unavailable, not yet complete) it is kept with <c>BadNoCommunication</c> (unknown ≠ gone, §5.1 T2, B2).
/// </summary>
private void Reconcile(MappingState[] states, HashSet<string> keys, bool full)
/// <returns>How many conditions were removed (#931 N7: a removal already carries RefreshRequired to their holders).</returns>
private int Reconcile(MappingState[] states, HashSet<string> keys, bool full)
{
if (_owner._sink() is not { } sink) return;
if (_owner._sink() is not { } sink) return 0;
HashSet<string>? listed = null;
if (full)
{
var listed = states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal);
listed = states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal);
foreach (var key in _materialised) if (!listed.Contains(key)) keys.Add(key);
}
var unknown = states.Any(x => !x.Known);
@@ -526,18 +784,31 @@ public sealed partial class ProjectedConditionAccess
foreach (var key in keys)
{
var update = Merge(states, key);
if (update is not null) { updates.Add(update); _materialised.Add(key); continue; }
if (update is not null)
{
updates.Add(update); _materialised.Add(key);
if (update.State.StateKnown) _unknownKeys.Remove(key); else _unknownKeys.Add(key);
continue;
}
if (!_materialised.Contains(key)) continue;
if (unknown) stale.Add(key);
else { _materialised.Remove(key); removals.Add(key); }
else { _materialised.Remove(key); _unknownKeys.Remove(key); removals.Add(key); }
}
if (removals.Count > 0) sink.RemoveConditions(ConnectionId, removals);
Volatile.Write(ref _unknownCount, _unknownKeys.Count);
Volatile.Write(ref _materialisedCount, _materialised.Count);
if (removals.Count > 0) { sink.RemoveConditions(ConnectionId, removals); _owner.Diagnostics.ConsumerRefreshRequired(ConnectionId); }
if (stale.Count > 0) sink.MarkConditionsStale(ConnectionId, stale);
if (updates.Count > 0) sink.ApplyConditions(updates);
_owner._ledger.SetMaterialised(ConnectionId, _materialised.Count);
// #931 N5: the held keys no contributing mapping lists are charged on top of the claims (counted on a full re-diff).
if (full) _unlisted = _materialised.Count(k => !listed!.Contains(k));
else _unlisted = Math.Min(_unlisted, _materialised.Count);
if (!_owner._ledger.SetMaterialised(ConnectionId, _materialised.Count, _unlisted))
_owner._log.LogWarning("Imported conditions: connection {Connection} holds {Count} condition(s) and the node is over its host condition caps",
ConnectionId, _materialised.Count);
if (updates.Count + removals.Count + stale.Count > 0)
_owner._log.LogDebug("Imported conditions: connection {Connection} applied {Updates} update(s), {Removals} removal(s), {Stale} kept stale",
ConnectionId, updates.Count, removals.Count, stale.Count);
return removals.Count;
}
/// <summary>One key across the connection's complete mappings: placements (primary first), latest record, SourceName.</summary>
@@ -1,5 +1,7 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
@@ -60,6 +62,18 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC
/// <summary>§9.3 L2: the host byte cap = measured per-condition bytes × 2,500 (the host condition cap).</summary>
public const long DefaultMaxImportedConditionBytes = BytesPerCondition * 2_500;
/// <summary>
/// #930 (N2/N3): the base in-stream retry delay of a mapping the origin refused DEFINITIVELY (<c>Denied</c>,
/// <c>NotFound</c>, <c>Unsupported</c>, for its item or its root metadata) or that is over capacity
/// (<see cref="ProjectedConditionMappingStatus.ConditionCapacity"/>); doubled per consecutive retry up to 4×. A transient
/// refusal or a snapshot timeout retries after <c>ConditionSnapshotTimeoutMilliseconds</c> × 2ⁿ (≤ 8×). Either way the
/// mapping's item is re-added on the OPEN stream — the healthy mappings are never re-snapshotted for it.
/// </summary>
public TimeSpan LongRetryDelay { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>#931 (N4): the ceiling of the exponential reconnect backoff after streams that end before their barrier.</summary>
public TimeSpan MaxReconnectDelay { get; init; } = TimeSpan.FromSeconds(60);
public static ProjectedConditionOptions Default { get; } =
new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1));
}
@@ -97,7 +111,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
private readonly ProjectedConditionOptions _options;
private readonly ILogger _log;
private readonly object _gate = new();
private readonly Dictionary<string, ConnectionRunner> _runners = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Mutated under <see cref="_gate"/> only; concurrent so a method call reads its runner's <c>Serving</c> without
/// taking <see cref="_gate"/> (#931 N6: <c>_gate</c> can sit behind a stop that waits on <c>_staleGate</c>).</summary>
private readonly ConcurrentDictionary<string, ConnectionRunner> _runners = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Review r1 S3/S4: a stopped runner's completion (its loop AND its removal) per connection; the next runner of
/// that connection awaits it before opening a stream or taking the materialised set, so the two never overlap.</summary>
private readonly Dictionary<string, ConnectionRunner> _stopping = new(StringComparer.OrdinalIgnoreCase);
@@ -109,9 +125,10 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
public ProjectedConditionAccess(IProjectedConditionMappings mappings, IGrpcDataAdapterConnectionSource connections,
DataOperationPolicy policy, Func<IProjectedConditionSink?>? sink, TimeProvider clock, ProjectedConditionOptions? options = null,
ILogger? logger = null)
ILogger? logger = null, DataConnectionConditionDiagnostics? diagnostics = null)
{
_mappings = mappings ?? throw new ArgumentNullException(nameof(mappings));
Diagnostics = diagnostics ?? new DataConnectionConditionDiagnostics();
_connections = connections ?? throw new ArgumentNullException(nameof(connections));
_policy = policy ?? throw new ArgumentNullException(nameof(policy));
_sink = sink ?? (() => Sink);
@@ -120,6 +137,24 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
_log = logger ?? NullLogger.Instance;
_ledger = new ConditionLedger(_options);
_mappings.Changed += OnMappingsChanged;
Diagnostics.AttachConsumer(CaptureConsumer);
}
/// <summary>A4: the diagnostics/metrics this runtime reports into (shared with the diagnostics readers).</summary>
public DataConnectionConditionDiagnostics Diagnostics { get; }
/// <summary>A4: one connection's consumer condition state; null when no current mapping of it is condition-bearing.</summary>
private DataConnectionConditionDiagnostics.ConsumerState? CaptureConsumer(string connectionId)
{
var mappings = _mappings.Current.Where(x => string.Equals(x.Mapping.DataConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)
&& x.Authority.IsActive && IsConditionBearing(x.Mapping)).ToArray();
if (mappings.Length == 0) return null;
// #931 N6 spirit: a diagnostics poll never takes _gate either.
if (!_runners.TryGetValue(connectionId, out var runner))
return new("idle", null, 0, 0, OrderMappings(mappings).Select(x => new ConditionMappingDiagnostics(x.Mapping.RemoteNamespaceMappingId,
ProjectedConditionMappingStatus.Pending.ToString(), 0, x.Mapping.MaxConditions)).ToArray(), _ledger.Total, _ledger.ConditionLimit);
var (state, snapshotAt, materialised, unknown, rows) = runner.Capture();
return new(state, snapshotAt, materialised, unknown, rows, _ledger.Total, _ledger.ConditionLimit);
}
/// <summary>The node manager the host binds once the server is up (used when no sink delegate was supplied).</summary>
@@ -222,7 +257,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
if (_disposed || _demand > 0) return;
stopped = _runners.Values.ToList();
_runners.Clear();
foreach (var runner in stopped) { runner.Stop(removeConditions: true); _stopping[runner.ConnectionId] = runner; }
foreach (var runner in stopped) { runner.Stop(removeConditions: true); Park(runner); }
}
}
@@ -245,9 +280,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
.ToDictionary(x => x.Key, x => OrderMappings(x).ToArray(), StringComparer.OrdinalIgnoreCase);
foreach (var id in _runners.Keys.Where(id => !byConnection.ContainsKey(id)).ToList())
{
_runners.Remove(id, out var gone);
_runners.TryRemove(id, out var gone);
gone!.Stop(removeConditions: true);
_stopping[id] = gone;
Park(gone);
}
foreach (var (id, mappings) in byConnection)
{
@@ -267,6 +302,27 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
}
}
/// <summary>
/// Under _gate: parks a removing runner so the connection's next runner awaits its removal (S3/S4). #931 N8: the entry
/// is dropped once that removal has finished — a removing stop hands over an empty set, so nothing is left to wait for,
/// and a connection that never returns no longer pins its last runner.
/// </summary>
private void Park(ConnectionRunner runner)
{
_stopping[runner.ConnectionId] = runner;
runner.Stopped.ContinueWith(_ =>
{
lock (_gate)
if (_stopping.TryGetValue(runner.ConnectionId, out var parked) && ReferenceEquals(parked, runner)) _stopping.Remove(runner.ConnectionId);
}, TaskScheduler.Default);
}
/// <summary>Test observation (#931 N8): whether a stopped runner of the connection is still parked.</summary>
public bool IsParked(string connectionId)
{
lock (_gate) return _stopping.ContainsKey(connectionId);
}
/// <summary>§5.2: Raw mappings before UNS, then mapping id ordinal (deployed configuration only).</summary>
internal static IEnumerable<ProjectedMappingPlacement> OrderMappings(IEnumerable<ProjectedMappingPlacement> mappings) =>
mappings.OrderBy(x => x.Mapping.Realm == DataRealm.Raw ? 0 : 1)
@@ -2998,7 +2998,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts(),
_catalogCoordinator?.ProjectedMappings?.CaptureDroppedByConnection()),
DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations,
OriginHistory: _dataConnections?.HistoryDiagnostics?.CaptureOrigin());
OriginHistory: _dataConnections?.HistoryDiagnostics?.CaptureOrigin(),
OriginConditions: _dataConnections?.ConditionDiagnostics?.CaptureOrigin());
Sender.Tell(snapshot);
}
@@ -253,7 +253,9 @@ public sealed class GrpcDataProjectedConditionAccessTests
f.Sink.Removed.Single().ShouldBe(Key("x"), "y is still listed by map-b");
f.Sink.Live.ShouldBe([Key("y")]);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.RefreshRequired.ShouldBeGreaterThan(refreshes, "clients are told the removal happened (§5.2)");
// #931 N7: the removal itself carries RefreshRequired to the holders (the sink's §5.2 "removal + RefreshRequired"), so
// the reset does not ask a second time.
f.Sink.RefreshRequired.ShouldBe(refreshes, "one RefreshRequired per capacity reset: the removal's");
}
private static Fixture TimedFixture(int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
@@ -316,7 +318,17 @@ public sealed class GrpcDataProjectedConditionAccessTests
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
f.Sink.RefreshRequired.ShouldBe(1, "S7: an incomplete barrier from a non-Good ack also requires refresh");
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("B2: an Unavailable mapping ends the stream; a new one retries it");
// #930 N2: the retry is IN-STREAM (the item re-added after the bounded wait) — the stream is not ended for it.
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
stream.AckAdd("map-a");
stream.Begin("map-a", total: 1);
stream.SnapshotRecords("map-a", Record(Key("w"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("w")));
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(300))).ShouldBeNull("no new stream: map-b is never re-snapshotted for map-a");
f.Sink.Applied.Count(u => u.State.ConditionKey == Key("x")).ShouldBe(1, "the healthy mapping's condition is not re-applied");
f.Sink.RefreshRequired.ShouldBe(1, "a recovered mapping needs no second RefreshRequired");
}
[Fact]
@@ -503,6 +515,162 @@ public sealed class GrpcDataProjectedConditionAccessTests
DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1));
}
// ---------------------------------------------------------------------------------------------------------------------
// #930 (N2/N3) and #931 (N4/N5/N7/N8) — A4
// ---------------------------------------------------------------------------------------------------------------------
private static Fixture LongRetryFixture(TimeSpan longRetry, int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
{
var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = longRetry }, mappings);
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs;
return f;
}
[Fact]
public async Task N2_a_definitive_refusal_waits_the_long_backoff_on_the_open_stream_never_storming_the_healthy_mapping()
{
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack(DataItemStatus.Denied, "map-a");
stream.Begin("map-b", total: 1);
stream.Records("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
// A transient refusal would be retried after the 300 ms snapshot timeout (and, before #930, the stream ended for it).
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(1.5))).ShouldBeNull("the stream is kept");
stream.AddsOf("map-a").ShouldBe(0, "Denied is definitive: the long backoff, not the snapshot timeout");
f.Sink.Applied.Count.ShouldBe(1, "map-b is not re-snapshotted");
f.Sink.RefreshRequired.ShouldBe(1);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
}
[Fact]
public async Task N2_an_unchanged_incomplete_set_on_a_new_stream_sends_no_second_RefreshRequired_a_changed_one_does()
{
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var first = await f.NextStreamAsync();
first.Ack(DataItemStatus.Denied, "map-a");
first.Begin("map-b", total: 1);
first.Records("map-b", Record(Key("x"), 3));
first.Complete("map-b");
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 1);
f.Sink.RefreshRequired.ShouldBe(1);
first.End();
var second = await f.NextStreamAsync();
second.Ack(DataItemStatus.Denied, "map-a"); // still refused: the same incomplete set
second.Begin("map-b", total: 1);
second.SnapshotRecords("map-b", Record(Key("x"), 4));
second.Complete("map-b");
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 2);
f.Sink.RefreshRequired.ShouldBe(1, "the clients were already told about map-a");
second.End();
var third = await f.NextStreamAsync();
third.Ack(DataItemStatus.Denied, "map-a", "map-b"); // a changed incomplete set ⇒ told again (positive control)
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 3);
f.Sink.RefreshRequired.ShouldBe(2);
}
[Fact]
public async Task N3_a_ConditionCapacity_mapping_is_re_added_in_stream_on_the_long_timer_and_recovers_when_under_its_limit()
{
await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(400), 30_000, ("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", total: 3); // over its MaxConditions
stream.Begin("map-b", total: 1);
stream.SnapshotRecords("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
stream.AckAdd("map-a");
stream.Begin("map-a", total: 2); // the origin dropped back under the limit
stream.SnapshotRecords("map-a", Record(Key("y"), 3), Record(Key("z"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")) && f.Sink.Live.Contains(Key("z")));
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(300))).ShouldBeNull("recovered on the open stream");
}
[Fact]
public async Task N3_a_retry_still_over_capacity_stays_ConditionCapacity_and_is_retried_again_never_removing_what_another_mapping_lists()
{
await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(300), 30_000, ("map-a", DataRealm.Raw, 1), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", total: 2);
stream.Begin("map-b", total: 1);
stream.SnapshotRecords("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
stream.AckAdd("map-a");
stream.Begin("map-a", total: 2);
await f.WaitAsync(() => stream.AddsOf("map-a") == 2); // backoff doubled, still in-stream
f.Sink.Removed.ShouldBeEmpty("map-b's key is never removed by map-a's retries (T2)");
f.Sink.Live.ShouldBe([Key("x")]);
}
[Fact]
public async Task N4_streams_that_never_reach_a_barrier_back_off_exponentially()
{
var options = Fixture.DefaultOptions with { MaxReconnectDelay = TimeSpan.FromMilliseconds(400) };
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10));
f.Connections.MetadataFails.Add(0); // every mapping's root fails ⇒ every stream ends before a barrier
using var demand = f.Access.AcquireEventDemand(null);
await Task.Delay(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
var calls = Volatile.Read(ref f.Connections.MetadataCalls);
calls.ShouldBeGreaterThan(2, "it keeps retrying");
// Fixed 50 ms reconnects would make ~40 attempts in 2 s; 50, 100, 200, 400, 400… makes ≤ ~8.
calls.ShouldBeLessThan(12);
}
[Fact]
public async Task N5_held_stale_keys_are_charged_beside_a_known_mappings_new_claim_but_overlap_an_unknown_mappings()
{
var options = Fixture.DefaultOptions with { MaxImportedConditionNodes = 3 * 49 }; // 3 conditions on the node
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = 300;
f.Mappings.Current[0].Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
f.Mappings.Current[1].Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
using var demand = f.Access.AcquireEventDemand(null);
var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("z"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 3);
first.End();
var second = await f.NextStreamAsync();
second.Ack();
second.Begin("map-b", total: 1);
second.SnapshotRecords("map-b", Record(Key("z"), 4));
second.Complete("map-b"); // map-a never answers: x, y held stale (unlisted)
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
// map-b (known) now re-lists z plus a new w: 4 conditions would be held — over the 3-condition cap.
second.Begin("map-b", total: 2);
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-b"] == ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.Live.ShouldNotContain(Key("w"));
f.Sink.Removed.ShouldBeEmpty("map-a is unknown: nothing is removed (T2)");
}
[Fact]
public async Task N8_a_stopped_runner_is_not_kept_parked_after_its_removal_finished()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var demand = f.Access.AcquireEventDemand(null)!;
var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
demand.Dispose();
await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1);
await f.WaitAsync(() => !f.Access.IsParked(Connection));
f.Access.RunnerReference(Connection).ShouldBeNull("a connection that never returns pins no runner");
stream.Disposed.ShouldBeTrue();
}
private sealed class Fixture : IAsyncDisposable
{
internal static readonly DataView DefaultRawPlacement =
@@ -637,6 +805,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
public Channel<FakeStream> Streams { get; } = Channel.CreateUnbounded<FakeStream>();
/// <summary>Metadata answers Bad for these root indexes (deployed order).</summary>
public HashSet<int> MetadataFails { get; } = [];
/// <summary>#931 N4: metadata requests made (one per stream attempt, plus in-stream root retries).</summary>
public int MetadataCalls;
/// <summary>The serving roles of the next streams (Primary when empty).</summary>
public Queue<string> Roles { get; } = new();
public int PrimarySubscribes;
@@ -664,7 +834,7 @@ public sealed class GrpcDataProjectedConditionAccessTests
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
Interlocked.Increment(ref owner.MetadataCalls) < 0 ? throw new InvalidOperationException() : Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
? new DataItemResult<DataMetadata>("0", DataItemStatus.Unavailable, null, null)
: new DataItemResult<DataMetadata>("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false,
DataOperations.Browse, 1, null, null, false), null)).ToArray());
@@ -691,14 +861,37 @@ public sealed class GrpcDataProjectedConditionAccessTests
private readonly TaskCompletionSource<OpenSubscription> _open = new(TaskCreationOptions.RunContinuationsAsynchronously);
private long _sequence;
public List<DataItemHandle> Removed { get; } = [];
/// <summary>#930: in-stream item re-adds (retries), in order.</summary>
public List<AddSubscriptionItems> Adds { get; } = [];
private readonly Dictionary<string, DataItemHandle> _current = new(StringComparer.Ordinal);
private ulong _nextHandle = 100;
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
if (command is OpenSubscription open) _open.TrySetResult(open);
if (command is RemoveSubscriptionItems remove) lock (Removed) Removed.AddRange(remove.Items);
if (command is AddSubscriptionItems add) lock (Adds) Adds.Add(add);
return Task.CompletedTask;
}
/// <summary>How many re-adds named <paramref name="mapping"/>.</summary>
public int AddsOf(string mapping) { lock (Adds) return Adds.Count(a => a.Items.Any(i => i.ClientItemId == mapping)); }
/// <summary>Acks the latest re-add of <paramref name="mapping"/> (Good ⇒ a fresh handle that later frames use).</summary>
public void AckAdd(string mapping, DataItemStatus status = DataItemStatus.Good)
{
AddSubscriptionItems add;
lock (Adds) add = Adds.Last(a => a.Items.Any(i => i.ClientItemId == mapping));
DataItemHandle? handle = null;
if (status == DataItemStatus.Good)
{
handle = new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, ++_nextHandle, 1);
lock (_current) _current[mapping] = handle;
}
_frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, add.CommandId,
[new DataSubscriptionItemAck(mapping, status, handle, null, status == DataItemStatus.Good ? null : "refused")]));
}
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
public ValueTask DisposeAsync() { Disposed = true; _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
@@ -706,13 +899,16 @@ public sealed class GrpcDataProjectedConditionAccessTests
public DataItemHandle HandleOf(string mapping)
{
lock (_current) if (_current.TryGetValue(mapping, out var current)) return current;
var index = Open.Items.Select((x, i) => (x, i)).Single(x => x.x.ClientItemId == mapping).i;
return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1);
}
public void Ack(params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
public void Ack(params string[] refused) => Ack(DataItemStatus.Unavailable, refused);
public void Ack(DataItemStatus refusal, params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
Open.Items.Select(x => refused.Contains(x.ClientItemId)
? new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Unavailable, null, x.Settings, "secondary")
? new DataSubscriptionItemAck(x.ClientItemId, refusal, null, x.Settings, "refused")
: new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray()));
/// <summary>Snapshot record frames exactly as the A2 origin frames them (is_snapshot, no total).</summary>