Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/CohortScaleFixture.cs
T
Joseph Doherty 5cccfd75ce fix(grpc-data): #994 projected cohorts batch, pace and scale past one item; busy origins no longer reset quiet streams
Wave 3 of the 2026-12-02 review (docs/reviews/2026-12-02/01-runtime.md R-2/3/7/8/9/10/12/13/21/22/23/24,
02-opcuaserver.md U-10/11/12/13).

Consumer (ProjectedDataAccess cohort):
- R-2: a cohort's OpenSubscription declared a snapshot budget of 1 item, which the origin uses to size the stream's
  handle table, so the 2nd item was refused LimitExceeded and the cohort re-opened in a loop (two projected items of
  one interval broke each other). Opens/adds/removes are now batched (IDataSubscriptionCommandLimits, <=256 items,
  bounded by estimated snapshot bytes) and paced (32 burst, 32/s, <=4 commands or snapshots outstanding).
- R-7: control events no longer share the bounded frame queue; a failed Remove can no longer Stop() the cohort.
- R-10: a local capacity refusal (TryPublishOrBackpressure -> CapacityExhausted) is retried for up to 2 s instead of
  invalidating healthy evidence and retiring the route.
- R-13: RemoteSubscription mutates its handle/version tables in place; the cohort caches the source per binding and
  drops the per-sample LINQ in EvidenceFor.
- R-8: only an unselectable endpoint arms the discovery backoff; a caller cancel is OperationCanceledException.
- R-24: the condition stream cancels and observes a pending frame read before disposing the enumerator.

Origin (DataSubscriptionSession / SamplePartition / SourceInterestLease):
- R-2 (found by the perf harness): the delivery index was sized MaxPendingFrames x 16 = 1024, so the 1025th item of a
  stream stopped the session after its ack; it now covers MaxMonitoredItems.
- R-3: interest reads count only own-ticket matches (scan budget separate), re-queue a lagging tick, and catch up from
  per-source last-change versions when the bounded history rolled off - no more "Source change history expired".
- R-9: a partition quiet bump resets a lease only when one of ITS sources was invalidated (per-source quiet version)
  or its binding retired; partition-wide invalidation still resets all.
- R-12: the per-item publish verdict is memoised per (catalog instance, authority generation) for <=1 s; Commit
  under the session lock re-checks identity only.
- R-21/R-22/R-23: registry prune is interval/capacity driven; a cleared history session refuses chunks; the snapshot
  barrier is decided and armed under the same gate its release is decided under.

Node manager: U-10 projected live items indexed by node; U-11 anchor removal / root-leaf swap tombstone the anchor's
own monitored node; U-12 per-parent child count; U-13 per-condition verdict index.

Also: Issue934_r1_N1 test clears its metadata failure before ending the stream (test-only sequencing race,
reproduced with a 200 ms delay; production behaviour correct).

Perf (Category=Perf, OTOPCUA_GRPCDATA_PERF=1): 10k-item cohort opens in 3.3 s / 80 commands / 1 stream (before: never
opens); 100 source versions at 1k/s -> 11,036 item values in 569 ms.
2026-12-03 11:59:26 -05:00

245 lines
14 KiB
C#

using System.Collections.Concurrent;
using Opc.Ua;
using Shouldly;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #994 (R-2/R-7/R-13): a consumer <see cref="ProjectedDataAccess"/> holding <c>N</c> projected demands, every one
/// subscribed through ONE cohort onto a REAL origin <see cref="DataSubscriptionSession"/> (real
/// <see cref="SubscriptionTransportCapacity"/>, default 128 commands/s per principal) — the end-to-end path the
/// per-item command loop broke. Values are counted per local identifier as they reach the publisher.
/// </summary>
internal sealed class CohortScaleFixture : IFederatedProjectionCatalog, IProjectedNodeLookup, IGrpcDataAdapterConnectionSource,
IProjectedValuePublisher, IDisposable
{
internal readonly LocalDataFixture Origin;
internal readonly SubscriptionTransportCapacity Capacity;
internal readonly DeferredSubscriptionDemand OriginDemand = new();
private readonly DataOperationPolicy _policy;
internal readonly RoleCarryingUserIdentity Caller;
internal readonly NodeId[] NodeIds;
private readonly Dictionary<NodeId, ProjectedVariableDefinition> _definitions = new();
private readonly Dictionary<string, ProjectedNodeProof> _proofs = new(StringComparer.Ordinal);
internal readonly ConcurrentDictionary<string, int> Baselines = new(StringComparer.Ordinal);
internal readonly ConcurrentDictionary<string, long> Latest = new(StringComparer.Ordinal);
internal int Retired, Publishes, Opens;
/// <summary>When set, TryPublish answers false (a capacity-refusing sink).</summary>
#pragma warning disable CS0649 // set by individual tests
internal volatile bool RefusePublish;
internal Func<ProjectedValueUpdate, bool>? PublishGate;
#pragma warning restore CS0649
internal readonly ConcurrentQueue<DataSubscriptionCommand> Commands = new();
private readonly ConcurrentQueue<IDataSubscription> _streams = new();
private DataSubscriptionSession? _session;
internal DataSubscriptionSession? Session => Volatile.Read(ref _session);
internal readonly int MaxBatchItems;
internal CohortScaleFixture(int items, int maxCommandsPerSecond = 128, int maxBatchItems = 100)
{
MaxBatchItems = maxBatchItems;
Capacity = new SubscriptionTransportCapacity(64, 16, 256L * 1024 * 1024, maxCommandsPerSecond: maxCommandsPerSecond);
var limits = new SubscriptionSessionLimits(128, 64, 1024 * 1024, TimeSpan.FromMinutes(5));
LocalDataFixture? peer = null;
Origin = new LocalDataFixture(additionalRawNodes: items, servingGeneration: 1, maxMonitoredItems: items + 16,
maxBatchItems: maxBatchItems, maxMessageBytes: 64 * 1024 * 1024, subscriptionFreshnessChallenges: true, hubBytes: 256L * 1024 * 1024,
targetSubscriptions: (context, target) => new CapturingService(this,
new LocalSubscriptionService(peer!.Services, context, target, OriginDemand, limits, Capacity)));
peer = Origin;
OriginDemand.Accept();
Origin.Publish(42);
_policy = new(Origin.Authority, new TriePermissionEvaluator(Origin.Authority.Tries, Origin.Clock), Origin.Clock);
Caller = new(new AnonymousIdentityToken(), [], Origin.Context.PrincipalId, Origin.Context.ApiKeyId,
Origin.Context.CredentialVersion, Origin.Context.CredentialExpiresUtc);
var serving = Origin.Serving;
var lease = new MetadataAuthorityLease(serving, new(1, 1, TimeSpan.FromSeconds(15)), Origin.Clock.GetTimestamp(),
TimeSpan.FromSeconds(15), TimeSpan.Zero, Origin.Clock);
var authority = Origin.Activation.CaptureAuthority();
NodeIds = new NodeId[items];
for (var i = 0; i < items; i++)
{
var origin = Origin.Raw with { Address = Origin.Raw.Address with { Identifier = Origin.Raw.Address.Identifier + i }, Subject = Origin.Raw.Subject + i };
var mapped = origin with { MappingId = "mapping", MappingRevision = 1, Subject = "Plant/branch/Speed" + i };
var subject = new MappedNamespaceSubject(mapped, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw,
Segments = ["Plant", "branch", "Speed" + i] }, ["folder"], serving, DataOperations.Subscribe, false);
var metadata = new DataMetadata(mapped, "Speed" + i, "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Subscribe, 1, null, null, false, Serving: serving);
var proof = new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", origin.Address), metadata, subject,
new([subject], 1, authority), lease, 1, metadata with { View = origin }, TimeSpan.FromSeconds(30));
var nodeId = new NodeId("projected-" + i, 2);
NodeIds[i] = nodeId;
_proofs[proof.LocalIdentifier] = proof;
_definitions[nodeId] = new(DataRealm.Raw, proof.LocalIdentifier, new NodeId("parent", 2), metadata, 1, () => true);
}
}
internal ProjectedDataAccess Create(int maxDemands) =>
new(this, this, this, _ => "link", _policy, this, Origin.Clock, new(maxDemands, 8, 64L * 1024 * 1024, 4));
internal IProjectedDemandLease[] AcquireAll(ProjectedDataAccess access)
{
var demands = new IProjectedDemandLease[NodeIds.Length];
for (var i = 0; i < NodeIds.Length; i++)
{
access.TryAcquire(NodeIds[i], Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue();
demands[i] = demand!;
}
return demands;
}
internal async Task WaitForAsync(Func<bool> condition, TimeSpan timeout, string because)
{
var deadline = DateTime.UtcNow + timeout;
while (!condition())
{
if (DateTime.UtcNow > deadline) throw new ShouldAssertException(because + " | " +
string.Join(" ", ProjectedStreamDiagnostics.Capture().Where(x => x.Value != 0).Select(x => x.Key + "=" + x.Value)) +
" | opens=" + Opens + " commands=" + string.Join(",", Commands.GroupBy(c => c.GetType().Name)
.Select(g => g.Key + "x" + g.Count() + "(" + g.Sum(CommandItems) + " items)")));
await Task.Delay(10);
}
}
private static int CommandItems(DataSubscriptionCommand command) => command switch
{
OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count, RemoveSubscriptionItems r => r.Items.Count,
ChallengeSubscriptionFreshness c => c.Items.Count, _ => 0
};
/// <summary>
/// Runs the fixture clock at about half real speed until disposed: the cohort's command pacer (32/s) and the origin's
/// per-second command window both read this clock, so a long open stalls on a frozen manual clock.
/// </summary>
internal IAsyncDisposable PumpClock()
{
var stop = new CancellationTokenSource();
var pump = Task.Run(async () =>
{
while (!stop.IsCancellationRequested)
{
try { await Task.Delay(20, stop.Token); } catch (OperationCanceledException) { break; }
Origin.Clock.Advance(TimeSpan.FromMilliseconds(10));
}
});
return new ClockPump(stop, pump);
}
private sealed class ClockPump(CancellationTokenSource stop, Task pump) : IAsyncDisposable
{
public async ValueTask DisposeAsync() { await stop.CancelAsync(); await pump; stop.Dispose(); }
}
internal void PublishVersion(long version, int value)
{
HubTest.Publish(Origin.Hub, Origin.Ticket, version, value);
Origin.Hub.ProcessPending();
}
/// <summary>Drops the current physical stream (origin restart / failover) so the cohort must re-open everything.</summary>
internal async Task DropStreamAsync()
{
foreach (var stream in _streams.ToArray()) await stream.DisposeAsync();
}
public TimeProvider Clock => Origin.Clock;
public event Action<string, long>? Invalidated { add { } remove { } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => throw new NotSupportedException();
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) =>
_proofs.TryGetValue(localId, out proof) && realm == DataRealm.Raw;
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin)
{
pin = _proofs.ContainsKey(localId) ? new NoopPin() : null;
return pin is not null;
}
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _definitions.TryGetValue(nodeId, out definition);
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) { nodeId = null; return false; }
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(Origin.Connection()));
public bool TryBind(ProjectedValueRoute route) => true;
/// <summary>#994 (R-10): this many publications are answered CapacityExhausted (a momentarily full sink).</summary>
internal int CapacityRefusals;
public ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList<ProjectedValueUpdate> updates)
{
if (Volatile.Read(ref CapacityRefusals) > 0 && Interlocked.Decrement(ref CapacityRefusals) >= 0) return ProjectedPublishOutcome.CapacityExhausted;
return TryPublish(updates) ? ProjectedPublishOutcome.Accepted : ProjectedPublishOutcome.Refused;
}
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates)
{
if (RefusePublish) return false;
foreach (var update in updates)
{
if (PublishGate is { } gate && !gate(update)) return false;
Interlocked.Increment(ref Publishes);
if (update.IsCompleteSnapshot) Baselines.AddOrUpdate(update.Route.LocalIdentifier, 1, (_, count) => count + 1);
Latest[update.Route.LocalIdentifier] = update.SourceVersion ?? 0;
}
return true;
}
public void Retire(ProjectedValueRoute route) => Interlocked.Increment(ref Retired);
public void Dispose() => Origin.Dispose();
private sealed class NoopPin : IDisposable { public void Dispose() { } }
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => connection.DisposeAsync();
}
private sealed class CapturingService(CohortScaleFixture owner, IDataSubscriptionService inner) : IDataSubscriptionService
{
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
var stream = await inner.SubscribeAsync(cancellationToken);
Interlocked.Increment(ref owner.Opens);
if (stream is DataSubscriptionSession session) Volatile.Write(ref owner._session, session);
var wrapped = new Recording(owner, stream);
owner._streams.Enqueue(wrapped);
return wrapped;
}
}
private sealed class Recording(CohortScaleFixture owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport, IDataSubscriptionCommandLimits,
IDataSubscriptionProvenance
{
public ServingIdentity Serving => owner.Origin.Serving;
// The origin was built with subscriptionFreshnessChallenges: true (as LocalDataRuntimeComposition is).
public bool SupportsFreshnessChallenges => true;
public int FreshnessMaxItems => owner.MaxBatchItems;
public int MaxCommandItems => (inner as IDataSubscriptionCommandLimits)?.MaxCommandItems ?? owner.MaxBatchItems;
private readonly ConcurrentDictionary<string, long> _challenges = new(StringComparer.Ordinal);
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
owner.Commands.Enqueue(command);
if (command is ChallengeSubscriptionFreshness challenge) _challenges[challenge.CommandId] = owner.Clock.GetTimestamp();
return inner.SendAsync(command, cancellationToken);
}
// Mirrors GrpcDataConnection.RemoteSubscription: a challenged value's upper age bound is its origin lower bound plus the
// consumer-side elapsed time since the challenge was sent (the local session leaves Upper unknown).
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var frame in inner.ReadAllAsync(cancellationToken))
{
if (frame is not DataSubscriptionValues values) { yield return frame; continue; }
var bounded = new List<DataSubscriptionValue>(values.Items.Count);
foreach (var item in values.Items)
{
var bounds = item.AgeBounds; long? observed = null;
if (item.FreshnessChallengeId is { } nonce && _challenges.TryGetValue(nonce, out var start) && bounds.Lower is { } lower)
{
observed = owner.Clock.GetTimestamp();
bounds = new(bounds.Lower, lower + owner.Clock.GetElapsedTime(start, observed.Value));
}
bounded.Add(item with { Sample = item.Sample with { Value = item.Sample.Value.Retain() }, AgeBounds = bounds,
FreshnessObservedTimestamp = observed });
}
yield return new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot, bounded, values);
}
}
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
}