fix(dcl): bind the reconnect re-subscribe loop to its session; shared supervisory advise ignores the first caller's token (DCL-4, DCL-9, WP3 task 3.3)

This commit is contained in:
Joseph Doherty
2026-12-03 09:57:13 -05:00
parent 2e8bede3b2
commit d52aff1bee
7 changed files with 317 additions and 14 deletions
@@ -2977,6 +2977,17 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
var batchSize = Math.Max(1, _options.SubscribeBatchSize);
var chunkDelay = _options.SubscribeBatchDelay;
// Session-bound background work (the re-subscribe loop below AND the re-seed further
// down) shares ONE token, created BEFORE either starts. CancelSessionWork — entering
// Reconnecting, an adapter swap, actor stop — cancels it. DCL-4: the loop used to have
// no token, so a loop left over from a dead session (a chunk wedged across a reconnect)
// carried on issuing its remaining chunks against the SAME adapter object's NEW client:
// duplicate OPC UA monitored items / MxGateway subscribes whose stale-generation results
// were then dropped without release.
CancelSessionWork();
_sessionWorkCts = new CancellationTokenSource();
var sessionToken = _sessionWorkCts.Token;
// Bounded, sequential chunks in ONE background task — replacing the previous
// "one fire-and-forget task per tag" storm (37,500 concurrent subscribes at the
// sizing target). Sequential because subscription creation on one session is
@@ -2987,8 +2998,22 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
{
for (var offset = 0; offset < allTags.Count; offset += batchSize)
{
if (offset > 0 && chunkDelay > TimeSpan.Zero)
await Task.Delay(chunkDelay);
try
{
if (offset > 0 && chunkDelay > TimeSpan.Zero)
await Task.Delay(chunkDelay, sessionToken);
}
catch (OperationCanceledException)
{
// Fall through to the cancellation check below.
}
if (sessionToken.IsCancellationRequested)
{
_log.Debug("[{0}] Reconnect re-subscribe abandoned at tag {1}/{2} — its session has ended",
_connectionName, offset, allTags.Count);
return;
}
var chunk = allTags.GetRange(offset, Math.Min(batchSize, allTags.Count - offset));
try
@@ -3022,9 +3047,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
// repopulated for the new adapter generation. Seeds delivered after registration is
// already established, so the ordering hazard does not apply here.
var reseedAdapter = _adapter;
CancelSessionWork();
_sessionWorkCts = new CancellationTokenSource();
var reseedToken = _sessionWorkCts.Token;
var reseedToken = sessionToken;
Task.Run(async () =>
{
try
@@ -370,7 +370,10 @@ public class MxGatewayDataConnection
// ONE gateway round trip per batch (SubscribeBulk = AddItem + Advise per tag in a
// single worker pass) instead of the historical 2 RPCs per tag.
var session = Volatile.Read(ref _session);
var outcomes = await _client!.SubscribeBulkAsync(tagPaths, cancellationToken);
// Dereference the session's client ONCE (DCL-4); results from a session that ended
// mid-call are not registered (the `current` check below).
var client = _client!;
var outcomes = await client.SubscribeBulkAsync(tagPaths, cancellationToken);
var current = session == Volatile.Read(ref _session);
var results = new List<TagSubscribeResult>(outcomes.Count);
foreach (var outcome in outcomes)
@@ -215,10 +215,13 @@ public class OpcUaDataConnection
IReadOnlyList<string> tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default)
{
EnsureConnected();
// Dereference the session's client ONCE (DCL-4): a reconnect swaps _client, and a call
// must run entirely against the client it started on.
var client = _client!;
// ONE shared callback for the whole batch — the client hands back the node id
// (== tag path for OPC UA), so no per-tag closure is needed.
var outcomes = await _client!.CreateSubscriptionsAsync(
var outcomes = await client.CreateSubscriptionsAsync(
tagPaths,
(nodeId, value, timestamp, statusCode) =>
{
@@ -47,6 +47,20 @@ public sealed class RealMxGatewayClient : IMxGatewayClient
// completed. A faulted advise is evicted so the next write retries.
private readonly ConcurrentDictionary<int, Lazy<Task>> _supervisoryAdvised = new();
/// <summary>
/// Cancelled on <see cref="DisposeAsync"/>. The SHARED supervisory-advise task runs under
/// this (plus <see cref="SharedSupervisoryAdviseTimeout"/>), never under the token of
/// whichever caller happened to create it (DCL-9).
/// </summary>
private readonly CancellationTokenSource _lifetime = new();
/// <summary>
/// Upper bound on one shared supervisory advise. The gateway session has no command
/// deadline of its own yet, so without a bound a hung advise would wedge every later
/// caller for that handle; a timed-out advise is evicted and the next caller retries.
/// </summary>
internal static readonly TimeSpan SharedSupervisoryAdviseTimeout = TimeSpan.FromSeconds(60);
// With no configured MXAccess write-user this connection behaves as a
// supervisory client: every advise defaults to AdviseSupervisory so writes are
// accepted. A configured write-user keeps the prior plain-advise behaviour.
@@ -517,6 +531,7 @@ public sealed class RealMxGatewayClient : IMxGatewayClient
/// <returns>A task that represents the asynchronous operation.</returns>
public async ValueTask DisposeAsync()
{
_lifetime.Cancel();
if (_session is not null) await _session.DisposeAsync().ConfigureAwait(false);
if (_client is not null) await _client.DisposeAsync().ConfigureAwait(false);
if (_galaxy is not null) await _galaxy.DisposeAsync().ConfigureAwait(false);
@@ -633,27 +648,46 @@ public sealed class RealMxGatewayClient : IMxGatewayClient
/// builds every other command). The result is remembered per handle; a failure is
/// not cached so the next attempt retries rather than wedging the item permanently.
/// </summary>
private async Task EnsureSupervisoryAdvisedAsync(int handle, CancellationToken ct)
internal async Task EnsureSupervisoryAdvisedAsync(int handle, CancellationToken ct)
{
// GetOrAdd + Lazy runs the advise at most once per handle; concurrent
// callers await the same Task and so never reach WriteBulk before it
// completes (default Lazy is thread-safe, factory runs once).
//
// DCL-9: the shared task must NOT capture the creating caller's token — a write's 30 s
// deadline firing would cancel the advise a concurrent, deadline-free subscribe is also
// awaiting, failing that subscribe as a tag-resolution error. The shared advise runs under
// the client lifetime (bounded by SharedSupervisoryAdviseTimeout); each caller applies its
// OWN token to its wait only.
var advise = _supervisoryAdvised.GetOrAdd(
handle,
h => new Lazy<Task>(() => AdviseSupervisoryCoreAsync(h, ct)));
h => new Lazy<Task>(() => RunSharedSupervisoryAdviseAsync(h)));
try
{
await advise.Value.ConfigureAwait(false);
await advise.Value.WaitAsync(ct).ConfigureAwait(false);
}
catch
{
// Evict the faulted entry (only if it's still the one we awaited) so the
// next write retries rather than caching a transient advise failure.
_supervisoryAdvised.TryRemove(new KeyValuePair<int, Lazy<Task>>(handle, advise));
// Evict a faulted/cancelled SHARED entry (only if it's still the one we awaited) so
// the next call retries rather than caching a transient advise failure. A caller that
// merely stopped waiting on its own token leaves the shared advise running for the
// others.
if (advise.Value.IsFaulted || advise.Value.IsCanceled)
_supervisoryAdvised.TryRemove(new KeyValuePair<int, Lazy<Task>>(handle, advise));
throw;
}
}
private async Task RunSharedSupervisoryAdviseAsync(int handle)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
cts.CancelAfter(SharedSupervisoryAdviseTimeout);
await (AdviseCoreOverride ?? AdviseSupervisoryCoreAsync)(handle, cts.Token).ConfigureAwait(false);
}
/// <summary>Test seam: replaces the gateway round trip of one supervisory advise.</summary>
internal Func<int, CancellationToken, Task>? AdviseCoreOverride { get; set; }
private async Task AdviseSupervisoryCoreAsync(int handle, CancellationToken ct)
{
var reply = await _session!.InvokeAsync(