diff --git a/docs/P9_MULTI_RCB_RECEIVE_CORRECTNESS.md b/docs/P9_MULTI_RCB_RECEIVE_CORRECTNESS.md new file mode 100644 index 00000000..d24b912d --- /dev/null +++ b/docs/P9_MULTI_RCB_RECEIVE_CORRECTNESS.md @@ -0,0 +1,35 @@ +# P9 — Reliable four-RCB dispatch candidate (2026-10-31) + +## Proven source-level defects, not an assumed SG7 root cause + +**Multi-monitor activation ordering:** `StartPersistentReportMonitorAsync` previously sent successful `RptEna`, performed post-enable readback and issued GI **before** registering its monitor target. The canonical MMS FIFO retains unsolicited frames, but another RCB's concurrent slice can drain it before the new RCB is registered. Such early initial-image frames then have no matching active target and cannot become values. This patch registers the monitor after acknowledged enable, **before** readback and GI. Exceptions after registration unregister the target. A Report arriving before the RptEna acknowledgment remains a known, deliberately unproven boundary: it cannot yet count as an authorized activation. + +**Unbounded per-RCB pending delivery:** the canonical receive FIFO already has count/byte limits, but the post-routing `ConcurrentQueue` had none. P9 atomically reserves bounded space (default 2048) before enqueue and never blocks the dispatcher. At capacity it retains the oldest frames, rejects new deliveries, increments a sticky per-RCB overflow counter, and exposes unverified continuity through the monitor summary and receive-slice result. Draining cannot erase evidence of a gap. Other RCBs remain independent. No implicit MMS polling, GI retry, mutation of RCB ownership, or vendor-specific exception was introduced. + +## Deterministic synthetic regression + +`MmsP9MultiRcbDispatchTests` uses original, synthetic BER-encoded MMS InformationReport PDUs and exercises decode, multi-RCB identity routing, typed member projection and bounded delivery. Cases include four independent SG7-style RCBs, abbreviated and full DataSet identities, burst ordering, contradictory RptID/DatSet quarantine, zero-frame activation, one slow RCB overflow, and unaffected peers. No external captures or proprietary implementation material was used. + +## Production gate + +This is an engine candidate, **not** proof that physical SG7 recovered from 56/77 to 77/77 or that all 4 RCB streams resumed. Confirm physical post-enable readback, ingress vs route vs projection, association lifetime, real first Report, and BufOvfl/EntryID/SqNum before closing ARSAS #707. P8 trial PR #763, ARSAS main/RC, v1.6.42 and pinned baseline remain untouched. A new Windows P9 artifact requires an exact-SHA ARSAS integration gate; this engine PR alone is not a Windows release. + + +## P9 read-mostly registry and reproducible performance evidence + +The previous per-frame dispatch called `SnapshotPersistentReportMonitors` under a registry lock and constructed a new `Where(...).ToArray()` even if the exact same four RCBs had been active for hours. This is a verified, avoidable allocation and lock on the MMS hot path. + +P9 now publishes immutable array snapshots only on membership mutations (activate, unregister, association reset) with a volatile publication/read. This removes the registry lock and repeated snapshot allocation from ordinary receive dispatch. Routing selection and typed projection are deliberately unchanged to preserve the proven fail-closed identity behavior. On association reset, the old monitors are marked stopped and the active snapshot is atomically cleared before draining; draining a slow monitor does not hold the registry lock. + +The xUnit P9 performance fixture produces local timing and `GC.GetAllocatedBytesForCurrentThread()` counts for a synthetic warm four-RCB MMS BER routing workload. Wire PDUs are prebuilt outside the measurement. One strict *structural* assertion verifies stable snapshot reads allocate at most a negligible fixed runtime overhead; **no speed/throughput SLA is asserted on shared GitHub Actions hardware**. Interpret latency and allocated bytes/frame only comparatively at matched exact commit/runtime/host. This is not first-report physical latency, full socket throughput, process RSS, lossless SOE, or a 77/77 field acceptance claim. + +Regression also verifies no snapshot republish for duplicate registration, the published registry is empty after association reset, all old RCB targets are stopped and pending queues drained, and old session frames cannot be admitted again. Future optimization of the identity selector should use these baseline metrics and retain the ambiguous identity tests rather than introducing vendor shortcuts. + + +## P9 dispatch finalization: allocation-free exact-ID selection and stop admission barrier + +The existing selector still created fresh LINQ `Where().ToArray()` candidate sets for *every* report after the registry snapshot was optimized. It now scans immutable active RCB references directly: exact RptID is a single-pass fast path; affinity and DataSet fallback are evaluated only if higher-priority identities fail. Existing precedence and fail-closed identity quarantine are preserved, including short DataSet names, duplicate identities, and zero-frame targets. An exact RptID-only synthetic allocation regression verifies repeated selection does not allocate candidate arrays. + +Previous stop/reset could drain a queue while a concurrent receive thread had reserved a delivery slot but had not enqueued its frame yet, leaving a stale frame behind after the final drain. A tiny nonblocking admission lease now lets lifecycle cleanup mark targets stopped, await only in-flight enqueue operations *off the hot path*, and then drain. `IsStopped` has volatile read/write semantics. A deterministic concurrent shutdown fixture starts four independent writers and validates that all old RCB queues are empty and never accept post-reset frames. + +These changes are source-level design and CI evidence, not claims of field-end-to-end latency, lossless operation or SG7 recovery. diff --git a/src/AR.Iec61850/Mms/MmsPersistentReportMonitor.cs b/src/AR.Iec61850/Mms/MmsPersistentReportMonitor.cs index ef5be0a7..eaa9fec5 100644 --- a/src/AR.Iec61850/Mms/MmsPersistentReportMonitor.cs +++ b/src/AR.Iec61850/Mms/MmsPersistentReportMonitor.cs @@ -14,6 +14,12 @@ public sealed class MmsPersistentReportMonitorSession private long _firstRoutedReportUtcTicks; private long _lastRoutedReportUtcTicks; private int _routedReportCount; + private int _pendingReportCount; + private int _pendingDeliveryOverflowCount; + private int _pendingAdmissionsInFlight; + private int _stopped; + private readonly int _pendingReportCapacity; + internal const int DefaultPendingReportCapacity = 2048; internal MmsPersistentReportMonitorSession( MmsReportSubscriptionPlan plan, @@ -23,8 +29,11 @@ internal MmsPersistentReportMonitorSession( bool deleteDynamicDataSetOnStop, bool dataSetCreated, bool reservationTouched, - bool enabledByThisClient) + bool enabledByThisClient, + int pendingReportCapacity = DefaultPendingReportCapacity) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pendingReportCapacity); + _pendingReportCapacity = Math.Min(pendingReportCapacity, DefaultPendingReportCapacity); Plan = plan; ReportControl = reportControl; OriginalDataSetReference = originalDataSetReference; @@ -48,8 +57,17 @@ internal MmsPersistentReportMonitorSession( public DateTimeOffset LastReportAt { get; internal set; } public int ReportCount { get; internal set; } public int PollReadCount { get; internal set; } - public bool IsStopped { get; internal set; } + // Concurrent dispatch observes stops without relying on an unsynchronized + // auto-property read from an old immutable RCB registry snapshot. + public bool IsStopped + { + get => Volatile.Read(ref _stopped) != 0; + internal set => Volatile.Write(ref _stopped, value ? 1 : 0); + } public int RoutedReportCount => Volatile.Read(ref _routedReportCount); + public int PendingReportCount => Volatile.Read(ref _pendingReportCount); + public int PendingDeliveryOverflowCount => Volatile.Read(ref _pendingDeliveryOverflowCount); + public bool IsDeliveryContinuityUnverified => PendingDeliveryOverflowCount > 0; public DateTimeOffset? FirstRoutedReportAt => ToUtcTimestamp(Volatile.Read(ref _firstRoutedReportUtcTicks)); public DateTimeOffset? LastRoutedReportAt => ToUtcTimestamp(Volatile.Read(ref _lastRoutedReportUtcTicks)); public MmsPersistentReportTrafficState TrafficState => IsStopped @@ -61,7 +79,75 @@ internal MmsPersistentReportMonitorSession( ? FirstRoutedReportAt.Value - StartedAt : null; - internal ConcurrentQueue PendingReports { get; } = new(); + private ConcurrentQueue PendingReports { get; } = new(); + + // Capacity must be reserved atomically before enqueue. No blocking, hidden + // frame replacement or unbounded memory growth when a consumer stalls. + internal bool TryQueuePendingReport(MmsReportFrame frame) + { + ArgumentNullException.ThrowIfNull(frame); + if (IsStopped) + return false; + + // A stop may begin after the first closed check. Acquire the small + // in-flight admission lease BEFORE checking again; lifecycle cleanup + // waits for leased writers outside the registry lock before draining. + Interlocked.Increment(ref _pendingAdmissionsInFlight); + try + { + if (IsStopped) + return false; + + while (true) + { + if (IsStopped) + return false; + var count = Volatile.Read(ref _pendingReportCount); + if (count >= _pendingReportCapacity) + { + // A shutdown is not consumer lag; do not inflate overflow. + if (IsStopped) + return false; + Interlocked.Increment(ref _pendingDeliveryOverflowCount); + return false; + } + if (Interlocked.CompareExchange(ref _pendingReportCount, count + 1, count) == count) + break; + } + + // The admission lease makes this enqueue visible to shutdown + // before it can drain; no frame can arrive behind the final drain. + PendingReports.Enqueue(frame); + return true; + } + finally + { + Interlocked.Decrement(ref _pendingAdmissionsInFlight); + } + } + + // Lifecycle-only barrier, never called from MMS receive hot path. All + // pending writers either completed enqueue or observed IsStopped before + // shutdown drains the queue. Later writers reject immediately. + internal void CompletePendingReportAdmissions() + { + IsStopped = true; + var spinner = new SpinWait(); + while (Volatile.Read(ref _pendingAdmissionsInFlight) != 0) + spinner.SpinOnce(); + } + + internal bool TryDequeuePendingReport(out MmsReportFrame frame) + { + if (PendingReports.TryDequeue(out var queued)) + { + Interlocked.Decrement(ref _pendingReportCount); + frame = queued; + return true; + } + frame = null!; + return false; + } internal void ObserveRoutedReport(MmsReportFrame frame) { @@ -74,7 +160,9 @@ internal void ObserveRoutedReport(MmsReportFrame frame) public string Summary => $"persistent report monitor: rcb={ReportControl.Reference}, dataset={Plan.DataSetReference}, mode={Plan.Mode}, " + - $"traffic={TrafficState}, routedReports={RoutedReportCount}, drainedReports={ReportCount}, stopped={IsStopped}"; + $"traffic={TrafficState}, routedReports={RoutedReportCount}, drainedReports={ReportCount}, " + + $"pendingReports={PendingReportCount}, pendingDeliveryOverflow={PendingDeliveryOverflowCount}, " + + $"deliveryContinuityUnverified={IsDeliveryContinuityUnverified}, stopped={IsStopped}"; private static DateTimeOffset? ToUtcTimestamp(long ticks) => ticks <= 0 ? null : new DateTimeOffset(ticks, TimeSpan.Zero); @@ -97,6 +185,8 @@ public sealed class MmsPersistentReportMonitorReceiveResult public IReadOnlyList PollReads { get; init; } = Array.Empty(); public IReadOnlyList WriteSteps { get; init; } = Array.Empty(); public string Message { get; init; } = string.Empty; + public int PendingDeliveryOverflowCount { get; init; } + public bool DeliveryContinuityUnverified { get; init; } } public sealed class MmsPersistentReportMonitorStopResult @@ -110,6 +200,9 @@ public sealed partial class MmsClientSession { private readonly object _persistentReportMonitorSync = new(); private readonly HashSet _persistentReportMonitors = new(); + // Immutable registry snapshot. The association receive loop must not lock + // and allocate a new array for every single InformationReport. + private MmsPersistentReportMonitorSession[] _activePersistentReportMonitors = Array.Empty(); private int _unroutedPersistentReportCount; /// @@ -147,6 +240,8 @@ public async Task StartPersistentReportMo var dataSetCreated = false; var reservationTouched = false; var enabledByThisClient = false; + MmsPersistentReportMonitorSession? registeredSession = null; + var keepRegisteredSession = false; var isDynamic = plan.Mode == MmsReportSubscriptionPlanMode.DynamicDataSet; try @@ -292,6 +387,14 @@ public async Task StartPersistentReportMo }; } + // Other RCB receive slices can drain the shared canonical FIFO during + // this method. Register this target before readback or GI so its + // initial image is never orphaned by a concurrent dispatcher. + registeredSession = new MmsPersistentReportMonitorSession( + plan, rcb, originalDataSetReference, isDynamic, deleteDynamicDataSetOnStop, + dataSetCreated, reservationTouched, enabledByThisClient); + RegisterPersistentReportMonitor(registeredSession); + var afterEnableSnapshot = await CaptureReportControlSnapshotAsync(rcb, "after-enable", cancellationToken).ConfigureAwait(false); rcbSnapshots.Add(afterEnableSnapshot); @@ -303,21 +406,11 @@ public async Task StartPersistentReportMo warnings.Add("GI=true write failed or is not supported by this RCB. Waiting for spontaneous/integrity reports only."); } - var session = new MmsPersistentReportMonitorSession( - plan, - rcb, - originalDataSetReference, - isDynamic, - deleteDynamicDataSetOnStop, - dataSetCreated, - reservationTouched, - enabledByThisClient); - RegisterPersistentReportMonitor(session); - + keepRegisteredSession = true; return new MmsPersistentReportMonitorStartResult { IsSuccess = true, - Session = session, + Session = registeredSession, WriteSteps = writes, Warnings = warnings, RcbSnapshots = rcbSnapshots, @@ -337,6 +430,13 @@ public async Task StartPersistentReportMo Message = $"Persistent report monitor start failed: {ex.GetType().Name}: {ex.Message}" }; } + finally + { + // Also runs for cancellation and unexpected exceptions: never leave + // an unowned monitor target registered after failed activation. + if (!keepRegisteredSession && registeredSession is not null) + UnregisterPersistentReportMonitor(registeredSession); + } } public async Task ReceivePersistentReportMonitorSliceAsync( @@ -380,7 +480,11 @@ await ReceiveAndDispatchPersistentReportsAsync( Reports = reports, PollReads = pollReads, WriteSteps = writes, - Message = $"Report monitor slice: reports={reports.Count}, pollReads={pollReads.Count}." + PendingDeliveryOverflowCount = session.PendingDeliveryOverflowCount, + DeliveryContinuityUnverified = session.IsDeliveryContinuityUnverified, + Message = $"Report monitor slice: reports={reports.Count}, pollReads={pollReads.Count}, " + + $"pendingDeliveryOverflow={session.PendingDeliveryOverflowCount}, " + + $"continuityUnverified={session.IsDeliveryContinuityUnverified}." }; } @@ -463,43 +567,70 @@ public async Task StopPersistentReportMoni }; } - private void RegisterPersistentReportMonitor(MmsPersistentReportMonitorSession session) + internal void RegisterPersistentReportMonitor(MmsPersistentReportMonitorSession session) { + ArgumentNullException.ThrowIfNull(session); + if (session.IsStopped) + throw new InvalidOperationException("Cannot register a stopped RCB monitor."); lock (_persistentReportMonitorSync) - _persistentReportMonitors.Add(session); + { + if (_persistentReportMonitors.Add(session)) + PublishPersistentReportMonitorSnapshotLocked(); + } } private void UnregisterPersistentReportMonitor(MmsPersistentReportMonitorSession session) { lock (_persistentReportMonitorSync) - _persistentReportMonitors.Remove(session); + { + // Mark stopped before a stale receiver can admit more frames, then + // publish the new registry for all future dispatch iterations. + session.IsStopped = true; + if (_persistentReportMonitors.Remove(session)) + PublishPersistentReportMonitorSnapshotLocked(); + } - while (session.PendingReports.TryDequeue(out _)) + session.CompletePendingReportAdmissions(); + while (session.TryDequeuePendingReport(out _)) { } } - private MmsPersistentReportMonitorSession[] SnapshotPersistentReportMonitors() - { - lock (_persistentReportMonitorSync) - return _persistentReportMonitors.Where(x => !x.IsStopped).ToArray(); - } + // Receive/dispatch is read-mostly. Membership changes happen only on + // activation, stop, and association reset. A volatile read gives every + // report an immutable, association-owned RCB registry with no monitor lock + // or per-frame snapshot allocation. Never publish mutable HashSet storage. + internal MmsPersistentReportMonitorSession[] SnapshotPersistentReportMonitors() + => Volatile.Read(ref _activePersistentReportMonitors); + + private void PublishPersistentReportMonitorSnapshotLocked() + => Volatile.Write(ref _activePersistentReportMonitors, + _persistentReportMonitors.Where(x => !x.IsStopped).ToArray()); - private void ClearPersistentReportMonitors() + internal void ClearPersistentReportMonitors() { + MmsPersistentReportMonitorSession[] retired; lock (_persistentReportMonitorSync) { - foreach (var session in _persistentReportMonitors) - { + retired = _persistentReportMonitors.ToArray(); + foreach (var session in retired) session.IsStopped = true; - while (session.PendingReports.TryDequeue(out _)) - { - } - } _persistentReportMonitors.Clear(); + Volatile.Write(ref _activePersistentReportMonitors, + Array.Empty()); Interlocked.Exchange(ref _unroutedPersistentReportCount, 0); } + + // Do not hold the registry lock while draining an overloaded RCB. + // In-flight stale snapshots see IsStopped and fail closed at queue admit. + foreach (var session in retired) + { + session.CompletePendingReportAdmissions(); + while (session.TryDequeuePendingReport(out _)) + { + } + } } private async Task ReceiveAndDispatchPersistentReportsAsync( @@ -616,11 +747,11 @@ await _receiveRouter.WaitForInformationReportAsync( private static void DrainPendingReports(MmsPersistentReportMonitorSession session, List destination) { - while (session.PendingReports.TryDequeue(out var frame)) + while (session.TryDequeuePendingReport(out var frame)) destination.Add(frame); } - private void RoutePersistentInformationReport(byte[] payload) + internal void RoutePersistentInformationReport(byte[] payload) { if (!MmsInformationReportDecoder.IsInformationReport(payload)) return; @@ -655,8 +786,16 @@ private void RoutePersistentInformationReport(byte[] payload) } var frame = MmsReportFrameMapper.Map(decoded, target.Plan.Members, DateTimeOffset.UtcNow); + if (!target.TryQueuePendingReport(frame)) + { + Interlocked.Increment(ref _unroutedPersistentReportCount); + LastReceiveRoutingSummary = target.IsStopped + ? $"InformationReport arrived while {target.ReportControl.Reference} was stopping; no post-stop projection." + : $"Routed InformationReport for {target.ReportControl.Reference} could not enter its bounded delivery queue. " + + $"Delivery continuity unverified; pendingOverflow={target.PendingDeliveryOverflowCount}."; + return; + } target.ObserveRoutedReport(frame); - target.PendingReports.Enqueue(frame); LastReceiveRoutingSummary = $"Routed InformationReport to {target.ReportControl.Reference} by {evidence}. RptID={RoutingTextOrDash(header.ReportId)}, DatSet={RoutingTextOrDash(header.DataSetReference)}."; } @@ -673,116 +812,162 @@ internal static bool HasRcbReportHeader(MmsInformationReport report) { ArgumentNullException.ThrowIfNull(active); ArgumentNullException.ThrowIfNull(header); - var candidates = active.Where(x => !x.IsStopped).ToArray(); - if (candidates.Length == 0) + + // The common exact-RptID path scans the immutable registry once. + // Do not allocate LINQ candidate arrays, even with many active RCBs. + // Keep exact ID > RCB affinity > exact DataSet > DataSet tail > + // single-active fallback, including the legacy ambiguity policy. + var reportId = NormalizeRoutingReference(header.ReportId); + var dataSet = NormalizeRoutingReference(header.DataSetReference); + var hasReportId = !string.IsNullOrWhiteSpace(reportId); + var hasDataSet = !string.IsNullOrWhiteSpace(dataSet); + var liveCount = 0; + var exactIdCount = 0; + MmsPersistentReportMonitorSession? sole = null; + MmsPersistentReportMonitorSession? exactIdCandidate = null; + + for (var i = 0; i < active.Count; i++) + { + var candidate = active[i]; + if (candidate.IsStopped) + continue; + sole = candidate; + liveCount++; + if (hasReportId && + NormalizeRoutingReference(candidate.ReportControl.ReportId) + .Equals(reportId, StringComparison.OrdinalIgnoreCase)) + { + exactIdCandidate = candidate; + exactIdCount++; + } + } + + if (liveCount == 0) { evidence = "no active persistent monitor"; return null; } - var dataSet = NormalizeRoutingReference(header.DataSetReference); - - // A recognized RptID cannot override a contradictory advertised DatSet. - // Some peers shorten the DatSet to LLN0$Name (or just Name), while - // others supply an exact LD/LN$Name. Match an abbreviated reference - // only at an explicit component boundary, never by a shared tail alone. - // An omitted DatSet preserves the legacy exact-RptID route. - bool ConflictsWithAdvertisedDataSet(MmsPersistentReportMonitorSession candidate) + if (exactIdCount == 1) { - if (string.IsNullOrWhiteSpace(dataSet)) - return false; - - var expected = NormalizeRoutingReference(candidate.Plan.DataSetReference); - if (string.IsNullOrWhiteSpace(expected)) - return false; // No authoritative plan identity to contradict. - - if (dataSet.Contains('/')) - return !expected.Equals(dataSet, StringComparison.OrdinalIgnoreCase); - - if (dataSet.Contains('.')) + if (ConflictsWithAdvertisedDataSet(exactIdCandidate!, dataSet)) { - // Domain omitted: require the entire LN.DataSet suffix. A - // matching bare DataSet name under another LN is not enough. - if (expected.Equals(dataSet, StringComparison.OrdinalIgnoreCase)) - return false; - var offset = expected.Length - dataSet.Length; - return offset <= 0 || - !expected.EndsWith(dataSet, StringComparison.OrdinalIgnoreCase) || - expected[offset - 1] != '/'; + evidence = "RptID/DatSet conflict: report was quarantined before process-value projection"; + return null; } - - // Some peers omit both domain and LN. Retain explicit tail-only - // compatibility, but do not route a *different* advertised tail. - return !RoutingTail(expected).Equals(dataSet, StringComparison.OrdinalIgnoreCase); + evidence = "exact RptID"; + return exactIdCandidate; } - var reportId = NormalizeRoutingReference(header.ReportId); - if (!string.IsNullOrWhiteSpace(reportId)) + if (hasReportId) { - var exactRptId = candidates - .Where(x => NormalizeRoutingReference(x.ReportControl.ReportId).Equals(reportId, StringComparison.OrdinalIgnoreCase)) - .ToArray(); - if (exactRptId.Length == 1) + MmsPersistentReportMonitorSession? affinityCandidate = null; + var affinityCount = 0; + for (var i = 0; i < active.Count; i++) { - if (ConflictsWithAdvertisedDataSet(exactRptId[0])) - { - evidence = "RptID/DatSet conflict: report was quarantined before process-value projection"; - return null; - } - evidence = "exact RptID"; - return exactRptId[0]; + var candidate = active[i]; + if (candidate.IsStopped || !HasRcbNameAffinity(reportId, candidate.ReportControl)) + continue; + affinityCandidate = candidate; + affinityCount++; } - var rcbAffinity = candidates.Where(x => HasRcbNameAffinity(reportId, x.ReportControl)).ToArray(); - if (rcbAffinity.Length == 1) + if (affinityCount == 1) { - if (ConflictsWithAdvertisedDataSet(rcbAffinity[0])) + if (ConflictsWithAdvertisedDataSet(affinityCandidate!, dataSet)) { evidence = "RptID/DatSet conflict: report was quarantined before process-value projection"; return null; } evidence = "RptID-to-RCB name affinity"; - return rcbAffinity[0]; + return affinityCandidate; } } - if (!string.IsNullOrWhiteSpace(dataSet)) + if (hasDataSet) { - var exactDataSet = candidates - .Where(x => NormalizeRoutingReference(x.Plan.DataSetReference).Equals(dataSet, StringComparison.OrdinalIgnoreCase)) - .ToArray(); - if (exactDataSet.Length == 1) + var dataSetTail = RoutingTail(dataSet); + var hasDataSetTail = !string.IsNullOrWhiteSpace(dataSetTail); + MmsPersistentReportMonitorSession? exactDataSetCandidate = null; + MmsPersistentReportMonitorSession? tailDataSetCandidate = null; + var exactDataSetCount = 0; + var tailDataSetCount = 0; + + for (var i = 0; i < active.Count; i++) { - evidence = "exact DataSet"; - return exactDataSet[0]; + var candidate = active[i]; + if (candidate.IsStopped) + continue; + var expected = NormalizeRoutingReference(candidate.Plan.DataSetReference); + if (expected.Equals(dataSet, StringComparison.OrdinalIgnoreCase)) + { + exactDataSetCandidate = candidate; + exactDataSetCount++; + } + if (hasDataSetTail && + RoutingTail(expected).Equals(dataSetTail, StringComparison.OrdinalIgnoreCase)) + { + tailDataSetCandidate = candidate; + tailDataSetCount++; + } } - var dataSetTail = RoutingTail(dataSet); - var tailMatches = candidates - .Where(x => RoutingTail(NormalizeRoutingReference(x.Plan.DataSetReference)).Equals(dataSetTail, StringComparison.OrdinalIgnoreCase)) - .ToArray(); - if (!string.IsNullOrWhiteSpace(dataSetTail) && tailMatches.Length == 1) + if (exactDataSetCount == 1) + { + evidence = "exact DataSet"; + return exactDataSetCandidate; + } + if (tailDataSetCount == 1) { evidence = "DataSet tail"; - return tailMatches[0]; + return tailDataSetCandidate; } } - if (candidates.Length == 1) + if (liveCount == 1) { - if (ConflictsWithAdvertisedDataSet(candidates[0])) + if (ConflictsWithAdvertisedDataSet(sole!, dataSet)) { evidence = "single-monitor DatSet conflict: report was quarantined before process-value projection"; return null; } evidence = "single active monitor fallback"; - return candidates[0]; + return sole; } evidence = "ambiguous report identity; report was not projected against an arbitrary DataSet"; return null; } + // Fail closed only when an advertised DataSet contradicts the selected RCB. + // Partial identity is valid on some relays, but suffixes must match at the + // appropriate LN/DataSet component boundary. + private static bool ConflictsWithAdvertisedDataSet( + MmsPersistentReportMonitorSession candidate, string dataSet) + { + if (string.IsNullOrWhiteSpace(dataSet)) + return false; + + var expected = NormalizeRoutingReference(candidate.Plan.DataSetReference); + if (string.IsNullOrWhiteSpace(expected)) + return false; + + if (dataSet.Contains('/')) + return !expected.Equals(dataSet, StringComparison.OrdinalIgnoreCase); + + if (dataSet.Contains('.')) + { + if (expected.Equals(dataSet, StringComparison.OrdinalIgnoreCase)) + return false; + var offset = expected.Length - dataSet.Length; + return offset <= 0 || + !expected.EndsWith(dataSet, StringComparison.OrdinalIgnoreCase) || + expected[offset - 1] != '/'; + } + + return !RoutingTail(expected).Equals(dataSet, StringComparison.OrdinalIgnoreCase); + } + private static bool HasRcbNameAffinity(string reportId, MmsReportControlCandidate reportControl) { var name = NormalizeRoutingReference(reportControl.Name); diff --git a/tests/AR.Iec61850.Tests/Mms/MmsP9AssociationDispatchPerformanceTests.cs b/tests/AR.Iec61850.Tests/Mms/MmsP9AssociationDispatchPerformanceTests.cs new file mode 100644 index 00000000..06d7314c --- /dev/null +++ b/tests/AR.Iec61850.Tests/Mms/MmsP9AssociationDispatchPerformanceTests.cs @@ -0,0 +1,125 @@ +using System.Diagnostics; +using AR.Iec61850.Mms; +using Xunit.Abstractions; + +namespace AR.Iec61850.Tests.Mms; + +/// +/// Deterministic synthetic workload with *observational* timing/allocation +/// evidence. Never gate CI against machine-specific throughput thresholds. +/// No physical IED, network or installed driver is required. +/// +public sealed class MmsP9AssociationDispatchPerformanceTests +{ + private readonly ITestOutputHelper _output; + + public MmsP9AssociationDispatchPerformanceTests(ITestOutputHelper output) + => _output = output; + + [Fact] + public async Task StableRegistryLookup_DoesNotAllocatePerReport() + { + await using var client = new MmsClientSession(); + var sessions = MmsP9MultiRcbDispatchTests.FourSessions(); + foreach (var session in sessions) + client.RegisterPersistentReportMonitor(session); + + var expected = client.SnapshotPersistentReportMonitors(); + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 16384; i++) + { + if (!ReferenceEquals(expected, client.SnapshotPersistentReportMonitors())) + throw new InvalidOperationException("Stable RCB membership unexpectedly republished."); + } + var bytes = GC.GetAllocatedBytesForCurrentThread() - before; + _output.WriteLine($"P9 registry: calls=16384, allocatedBytes={bytes}, " + + $"bytesPerLookup={(double)bytes / 16384:0.0000}"); + Assert.InRange(bytes, 0, 256); + Assert.Equal(4, expected.Length); + } + + [Fact] + public async Task ConcurrentShutdown_PreventsPostResetPendingFrameAdmission() + { + await using var client = new MmsClientSession(); + var sessions = MmsP9MultiRcbDispatchTests.FourSessions(pendingCapacity: 128); + foreach (var session in sessions) + client.RegisterPersistentReportMonitor(session); + + var frame = new MmsReportFrame(); + using var start = new ManualResetEventSlim(false); + var writers = Enumerable.Range(0, 4).Select(index => Task.Run(() => + { + start.Wait(); + for (var i = 0; i < 4096; i++) + sessions[index].TryQueuePendingReport(frame); + })).ToArray(); + + start.Set(); + // Concurrent shutdown, not a continuation that waits for all writers. + client.ClearPersistentReportMonitors(); + await Task.WhenAll(writers); + + Assert.Empty(client.SnapshotPersistentReportMonitors()); + foreach (var session in sessions) + { + Assert.True(session.IsStopped); + Assert.Equal(0, session.PendingReportCount); + Assert.False(session.TryQueuePendingReport(frame)); + } + } + + [Fact] + public async Task FourRcbBerDispatch_RecordsLatencyAndAllocationsWithoutFlakySpeedGate() + { + await using var client = new MmsClientSession(); + var sessions = MmsP9MultiRcbDispatchTests.FourSessions(); + foreach (var session in sessions) + client.RegisterPersistentReportMonitor(session); + + var pdus = sessions.Select(s => MmsP9MultiRcbDispatchTests.BuildReport( + s.ReportControl.ReportId, s.Plan.DataSetReference.Replace('.', '$'), true)).ToArray(); + + // Same measured path as production (decode + identity + projection + + // bounded FIFO), but prebuild wire bytes so fixture generation is not + // falsely counted as decoder/dispatch cost. + for (var warmup = 0; warmup < 8; warmup++) + RouteAndDrainOneRound(client, sessions, pdus); + + const int rounds = 128; + const int frameCount = rounds * 4; + var allocatedBefore = GC.GetAllocatedBytesForCurrentThread(); + var started = Stopwatch.GetTimestamp(); + for (var i = 0; i < rounds; i++) + RouteAndDrainOneRound(client, sessions, pdus); + var elapsed = Stopwatch.GetElapsedTime(started); + var allocations = GC.GetAllocatedBytesForCurrentThread() - allocatedBefore; + + _output.WriteLine( + $"P9 four-RCB BER dispatch: frames={frameCount}, durationMs={elapsed.TotalMilliseconds:0.###}, " + + $"framesPerSecond={frameCount / Math.Max(elapsed.TotalSeconds, 1e-9):0.##}, " + + $"allocatedBytes={allocations}, bytesPerFrame={(double)allocations / frameCount:0.##}. " + + "Synthetic diagnostic workload, not a field/production SLA."); + foreach (var session in sessions) + { + Assert.Equal(rounds + 8, session.RoutedReportCount); + Assert.Equal(0, session.PendingReportCount); + Assert.Equal(0, session.PendingDeliveryOverflowCount); + } + Assert.Equal(0, client.UnroutedPersistentReportCount); + Assert.True(elapsed >= TimeSpan.Zero); + } + + private static void RouteAndDrainOneRound( + MmsClientSession client, + MmsPersistentReportMonitorSession[] sessions, + byte[][] pdus) + { + for (var index = 0; index < sessions.Length; index++) + { + client.RoutePersistentInformationReport(pdus[index]); + if (!sessions[index].TryDequeuePendingReport(out _)) + throw new InvalidOperationException("No exact RCB delivery during benchmark workload."); + } + } +} diff --git a/tests/AR.Iec61850.Tests/Mms/MmsP9MultiRcbDispatchTests.cs b/tests/AR.Iec61850.Tests/Mms/MmsP9MultiRcbDispatchTests.cs new file mode 100644 index 00000000..b4dc9a24 --- /dev/null +++ b/tests/AR.Iec61850.Tests/Mms/MmsP9MultiRcbDispatchTests.cs @@ -0,0 +1,212 @@ +using AR.Iec61850.Asn1; +using AR.Iec61850.Mms; + +namespace AR.Iec61850.Tests.Mms; + +/// +/// Project-owned synthetic MMS InformationReport BER, not real station traffic. +/// Tests the shared MMS decode -> RCB selection -> typed projection -> delivery. +/// +public sealed class MmsP9MultiRcbDispatchTests +{ + [Fact] + public async Task FourRcbBurst_RoutesShortAndExactDataSetsWithoutCrossProjection() + { + await using var client = new MmsClientSession(); + var sessions = FourSessions(); + foreach (var session in sessions) + client.RegisterPersistentReportMonitor(session); + + var router = new MmsReceiveRouter(); + for (var round = 0; round < 12; round++) + { + foreach (var session in sessions.Reverse()) + { + var dataSet = (round % 3) switch + { + 0 => session.Plan.DataSetReference.Replace('.', '$'), + 1 => "LLN0$" + session.Plan.DataSetReference.Split('.').Last(), + _ => session.Plan.DataSetReference.Split('.').Last() + }; + router.Route(BuildReport(session.ReportControl.ReportId, dataSet, round % 2 == 0)); + } + } + + Assert.Equal(48, router.QueuedInformationReportCount); + while (router.TryDequeueInformationReport(out var envelope)) + client.RoutePersistentInformationReport(envelope.PresentationPayload); + + Assert.Equal(0, client.UnroutedPersistentReportCount); + foreach (var session in sessions) + { + Assert.Equal(12, session.RoutedReportCount); + Assert.Equal(12, session.PendingReportCount); + Assert.Equal(MmsPersistentReportTrafficState.TrafficProven, session.TrafficState); + Assert.Equal(0, session.PendingDeliveryOverflowCount); + for (var round = 0; round < 12; round++) + { + Assert.True(session.TryDequeuePendingReport(out var frame)); + Assert.Single(frame.Values); + Assert.Equal(session.Plan.Members[0].UserReference, frame.Values[0].Member?.UserReference); + Assert.Equal(round % 2 == 0, (bool)frame.Values[0].Value!.Value!); + } + Assert.Equal(0, session.PendingReportCount); + } + } + + [Fact] + public async Task ConflictingIdentity_AndZeroFrameTarget_DoNotFabricateLiveEvidence() + { + await using var client = new MmsClientSession(); + var sessions = FourSessions(); + foreach (var session in sessions) + client.RegisterPersistentReportMonitor(session); + + // Same association: explicit RptID A conflicts with DataSet B. + client.RoutePersistentInformationReport(BuildReport("RPT_A", "LLN0$TT3DataSet02", true)); + // Unknown report identity with four active targets is deliberately ambiguous. + client.RoutePersistentInformationReport(BuildReport("UNBOUND", null, true)); + client.RoutePersistentInformationReport(BuildReport("RPT_I", "TT6DataSet4", false)); + + Assert.Equal(2, client.UnroutedPersistentReportCount); + Assert.Equal(0, sessions[0].RoutedReportCount); + Assert.Equal(0, sessions[1].RoutedReportCount); + Assert.Equal(1, sessions[2].RoutedReportCount); + Assert.Equal(0, sessions[3].RoutedReportCount); + Assert.Equal(MmsPersistentReportTrafficState.ArmedAwaitingTraffic, sessions[3].TrafficState); + } + + [Fact] + public async Task SlowRcb_BoundedOverflowStaysExplicit_IndependentRcbsKeepReceiving() + { + await using var client = new MmsClientSession(); + var sessions = FourSessions(pendingCapacity: 8); + foreach (var session in sessions) + client.RegisterPersistentReportMonitor(session); + + for (var i = 0; i < 80; i++) + client.RoutePersistentInformationReport(BuildReport("RPT_A", "LLN0$TT6DataSet3", true)); + + client.RoutePersistentInformationReport(BuildReport("RPT_B", "LLN0$TT3DataSet02", false)); + client.RoutePersistentInformationReport(BuildReport("RPT_I", "LLN0$TT6DataSet4", true)); + + Assert.Equal(8, sessions[0].PendingReportCount); + Assert.Equal(8, sessions[0].RoutedReportCount); + Assert.Equal(72, sessions[0].PendingDeliveryOverflowCount); + Assert.True(sessions[0].IsDeliveryContinuityUnverified); + Assert.Contains("deliveryContinuityUnverified=True", sessions[0].Summary); + Assert.Equal(72, client.UnroutedPersistentReportCount); + Assert.Equal(1, sessions[1].RoutedReportCount); + Assert.Equal(1, sessions[2].RoutedReportCount); + Assert.Equal(MmsPersistentReportTrafficState.ArmedAwaitingTraffic, sessions[3].TrafficState); + + for (var i = 0; i < 8; i++) + Assert.True(sessions[0].TryDequeuePendingReport(out _)); + Assert.Equal(0, sessions[0].PendingReportCount); + + // Draining memory never erases previously detected continuity failure. + client.RoutePersistentInformationReport(BuildReport("RPT_A", "LLN0$TT6DataSet3", false)); + Assert.Equal(1, sessions[0].PendingReportCount); + Assert.True(sessions[0].IsDeliveryContinuityUnverified); + } + + [Fact] + public async Task AssociationRegistry_UsesStableSnapshot_UntilMembershipChangesOrReset() + { + await using var client = new MmsClientSession(); + var sessions = FourSessions(); + foreach (var session in sessions) + client.RegisterPersistentReportMonitor(session); + + var snapshot = client.SnapshotPersistentReportMonitors(); + Assert.Equal(4, snapshot.Length); + for (var i = 0; i < 1024; i++) + Assert.Same(snapshot, client.SnapshotPersistentReportMonitors()); + + // Re-registering the same target is idempotent and does not force + // allocation or alter report ownership. + client.RegisterPersistentReportMonitor(sessions[0]); + Assert.Same(snapshot, client.SnapshotPersistentReportMonitors()); + + client.RoutePersistentInformationReport( + BuildReport("RPT_A", "LLN0$TT6DataSet3", true)); + Assert.Equal(1, sessions[0].PendingReportCount); + + // A reconnect must revoke every RCB of the old association, publish + // an empty registry atomically and drain its old pending deliveries. + client.ClearPersistentReportMonitors(); + Assert.Empty(client.SnapshotPersistentReportMonitors()); + Assert.All(sessions, session => + { + Assert.True(session.IsStopped); + Assert.Equal(0, session.PendingReportCount); + Assert.False(session.TryQueuePendingReport(new MmsReportFrame())); + }); + Assert.Equal(0, client.UnroutedPersistentReportCount); + } + + internal static MmsPersistentReportMonitorSession[] FourSessions(int pendingCapacity = 2048) => + [ + Create("BrcbA01", "RPT_A", "TT6DataSet3", pendingCapacity), + Create("BrcbB01", "RPT_B", "TT3DataSet02", pendingCapacity), + Create("BrcbI01", "RPT_I", "TT6DataSet4", pendingCapacity), + Create("BrcbD01", "RPT_D", "TT3DataSet01", pendingCapacity) + ]; + + private static MmsPersistentReportMonitorSession Create(string name, string reportId, string dataSet, int capacity) + { + var reference = "SG7_BCUMaster/LLN0." + dataSet; + var rcb = new MmsReportControlCandidate + { + Domain = "SG7_BCUMaster", + LogicalNode = "LLN0", + FunctionalConstraint = "BR", + Name = name, + Reference = "SG7_BCUMaster/LLN0.BR." + name, + ReportId = reportId, + DataSetReference = reference, + Buffered = true + }; + var plan = new MmsReportSubscriptionPlan + { + Mode = MmsReportSubscriptionPlanMode.StaticDataSet, + Status = MmsReportSubscriptionPlanStatus.ReadyRequiresWrite, + ReportControl = rcb, + DataSetReference = reference, + Members = [new MmsDataSetDirectoryMember + { + UserReference = "SG7_BCUMaster/GGIO1." + name + ".stVal", + FunctionalConstraint = "ST" + }] + }; + return new MmsPersistentReportMonitorSession( + plan, rcb, reference, isDynamic: false, deleteDynamicDataSetOnStop: false, + dataSetCreated: false, reservationTouched: false, enabledByThisClient: true, + pendingReportCapacity: capacity); + } + + internal static byte[] BuildReport(string reportId, string? dataSet, bool value) + { + var fields = new List + { + MmsDataValue.VisibleString(reportId), + // 10-bit OptFlds: bit 4 indicates DataSet name. + MmsDataValue.BitString(6, [dataSet is null ? (byte)0x00 : (byte)0x08, 0x00]) + }; + if (dataSet is not null) + fields.Add(MmsDataValue.VisibleString(dataSet)); + fields.Add(MmsDataValue.BitString(7, [0x80])); // one included DataSet member + fields.Add(MmsDataValue.Boolean(value)); + + var encodedResults = fields.SelectMany(MmsDataCodec.Encode).ToArray(); + var variableList = BerWriter.EncodeTlv( + 0xA1, + BerWriter.EncodeTlv(0x1A, BerWriter.EncodeAscii("SG7_BCUMaster")) + .Concat(BerWriter.EncodeTlv(0x1A, BerWriter.EncodeAscii("LLN0$RPT"))) + .ToArray()); + var informationReport = BerWriter.EncodeTlv( + 0xA0, variableList.Concat(BerWriter.EncodeTlv(0xA0, encodedResults)).ToArray()); + return MmsPresentation.WrapIsoPresentationPData( + BerWriter.EncodeTlv(0xA3, informationReport)); + } +} diff --git a/tests/AR.Iec61850.Tests/Mms/MmsPersistentReportRoutingTests.cs b/tests/AR.Iec61850.Tests/Mms/MmsPersistentReportRoutingTests.cs index 3fd4cb58..0069ce29 100644 --- a/tests/AR.Iec61850.Tests/Mms/MmsPersistentReportRoutingTests.cs +++ b/tests/AR.Iec61850.Tests/Mms/MmsPersistentReportRoutingTests.cs @@ -218,6 +218,73 @@ public void Selector_DoesNotProjectAmbiguousReportAgainstArbitraryMembers() Assert.Contains("ambiguous", evidence, StringComparison.OrdinalIgnoreCase); } + [Fact] + public void Selector_ExactReportIdDoesNotAllocateCandidateArraysPerFrame() + { + var candidates = new[] + { + CreateSession("BrcbA01", "RPT_A", "SG7_BCUMaster/LLN0.TT6DataSet3"), + CreateSession("BrcbB01", "RPT_B", "SG7_BCUMaster/LLN0.TT3DataSet02"), + CreateSession("BrcbI01", "RPT_I", "SG7_BCUMaster/LLN0.TT6DataSet4"), + CreateSession("BrcbD01", "RPT_D", "SG7_BCUMaster/LLN0.TT3DataSet01") + }; + var header = new MmsReportHeader { ReportId = "RPT_A" }; + for (var i = 0; i < 256; i++) + MmsClientSession.SelectPersistentReportMonitor(candidates, header, out _); + + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 8192; i++) + { + var result = MmsClientSession.SelectPersistentReportMonitor(candidates, header, out _); + if (!ReferenceEquals(candidates[0], result)) + throw new InvalidOperationException("Exact Report ID routing changed in the measured dispatch path."); + } + var bytes = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.InRange(bytes, 0, 512); + } + + [Fact] + public void Selector_StoppedRcbCannotShadowLiveRptIdOrDataSetIdentity() + { + var retired = CreateSession("BrcbA01", "DUPLICATE", "IEDLD0/LLN0.DS_A"); + var live = CreateSession("BrcbB01", "DUPLICATE", "IEDLD0/LLN0.DS_A"); + retired.IsStopped = true; + var selected = MmsClientSession.SelectPersistentReportMonitor( + [retired, live], + new MmsReportHeader { ReportId = "DUPLICATE", DataSetReference = "IEDLD0/LLN0$DS_A" }, + out var evidence); + Assert.Same(live, selected); + Assert.Equal("exact RptID", evidence); + } + + [Fact] + public void Selector_ConflictingAndAmbiguousCandidatesFailClosedAcrossOrdering() + { + var a = CreateSession("BrcbA01", "SAME", "IEDLD0/LLN0.DS_A"); + var b = CreateSession("BrcbB01", "SAME", "IEDLD0/LLN0.DS_B"); + var third = CreateSession("BrcbC01", "DIFFERENT", "IEDLD0/LLN0.DS_A"); + foreach (var candidates in new[] + { + new[] { a, b, third }, + new[] { third, b, a }, + new[] { b, a, third } + }) + { + // Duplicate RptID cannot substitute for a unique identity. + Assert.Null(MmsClientSession.SelectPersistentReportMonitor( + candidates, new MmsReportHeader { ReportId = "SAME" }, out var conflict)); + Assert.Contains("ambiguous", conflict); + + // Exact RptID on a different target with conflicting DatSet + // remains quarantined even though a DataSet-only target exists. + Assert.Null(MmsClientSession.SelectPersistentReportMonitor( + candidates, + new MmsReportHeader { ReportId = "DIFFERENT", DataSetReference = "IEDLD0/LLN0$DS_B" }, + out var mismatch)); + Assert.Contains("quarantined", mismatch); + } + } + private static MmsPersistentReportMonitorSession CreateSession(string rcbName, string reportId, string dataSet) { var rcb = new MmsReportControlCandidate