Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions src/AR.Iec61850/Mms/MmsClientSession.SmartDiscovery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -221,11 +221,13 @@ await EnrichReportInventorySmartAsync(
var dataSetDirectorySummary = options.ReadDataSetDirectories
? $"dataset directories={successfulDataSetDirectories}/{dataSetReferences.Length}, dataset members={discoveredDataSetMembers}"
: "dataset directories=deferred";
var probeBudget = Math.Min(inventory.ReportControls.Count,
Math.Max(0, options.MaxReportAttributeProbes));
var reportSummary = !options.ProbeReportAttributes
? "report enrichment=deferred"
: reportEnrichmentInterrupted
? "report enrichment=partial"
: "report enrichment=completed";
? $"report enrichment=partial (budget {probeBudget}/{inventory.ReportControls.Count} observed RCBs)"
: $"report enrichment=completed (budget {probeBudget}/{inventory.ReportControls.Count} observed RCBs; not full binding proof)";

UpdateSmartDiscoveryCompleteness(snapshot, iedDirectory, inventory, dataSetDirectories);
var kpi = LastSmartDiscoveryKpi;
Expand Down Expand Up @@ -269,12 +271,11 @@ private async Task EnrichReportInventorySmartAsync(
!IsMmsInitiated)
return;

var candidates = inventory.ReportControls
.OrderByDescending(control => control.Buffered)
.ThenByDescending(control =>
control.LogicalNode.Equals("LLN0", StringComparison.OrdinalIgnoreCase))
.Take(maxReportAttributeProbes)
.ToArray();
// Exact live RCBs only. Round-robin across observed numbered families
// before spending the finite 64-Read enrichment budget on sibling
// client slots. No new GetNameList, inferred binding or RCB write.
var candidates = MmsSmartDiscoveryPolicy.SelectReportEnrichmentCandidates(
inventory.ReportControls, maxReportAttributeProbes);

// The association's negotiatedCalling is authoritative. Never create
// speculative associations or exceed the transport's existing window.
Expand Down
66 changes: 66 additions & 0 deletions src/AR.Iec61850/Mms/MmsSmartDiscoveryPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,72 @@ public static int ResolveReportEnrichmentWorkers(int effectiveWindow, int candid
=> candidateCount <= 0 ? 0 :
Math.Min(Math.Clamp(effectiveWindow, 1, 8), candidateCount);

/// <summary>
/// Fairly samples exact, MMS-observed RCB instances under a fixed Read
/// budget. Large peers may expose many numbered client slots per configured
/// RCB family. Reading the first N sorted instances then biases discovery
/// toward only a few DataSets and can mislead an application into treating
/// every other DataSet as unreportable. One observed member per family is
/// read before spending more of the same budget on that family's siblings.
///
/// The family key is a READ scheduling hint only: no RCB, DataSet binding,
/// availability, or write authority is fabricated from the prefix.
/// Every result must still be proven by an exact MMS Read of the observed
/// instance. The peer-negotiated worker window and original cap remain.
/// </summary>
public static MmsReportControlCandidate[] SelectReportEnrichmentCandidates(
IEnumerable<MmsReportControlCandidate> observed, int maxReads)
{
ArgumentNullException.ThrowIfNull(observed);
if (maxReads <= 0)
return Array.Empty<MmsReportControlCandidate>();

var families = observed
.Where(rcb => !string.IsNullOrWhiteSpace(rcb.Reference))
.DistinctBy(rcb => rcb.Reference, StringComparer.OrdinalIgnoreCase)
.OrderByDescending(rcb => rcb.Buffered)
.ThenBy(rcb => rcb.Domain, StringComparer.OrdinalIgnoreCase)
.ThenBy(rcb => rcb.LogicalNode, StringComparer.OrdinalIgnoreCase)
.ThenBy(rcb => rcb.FunctionalConstraint, StringComparer.OrdinalIgnoreCase)
.ThenBy(rcb => rcb.Name, StringComparer.OrdinalIgnoreCase)
.ThenBy(rcb => rcb.Reference, StringComparer.Ordinal)
.GroupBy(rcb => string.Concat(
rcb.Domain, "\u001F", rcb.LogicalNode, "\u001F",
rcb.FunctionalConstraint, "\u001F", RcbReadSchedulingFamily(rcb.Name)),
StringComparer.OrdinalIgnoreCase)
.Select(group => group.ToArray())
.ToArray();

var result = new List<MmsReportControlCandidate>(Math.Min(maxReads, families.Sum(x => x.Length)));
for (var depth = 0; result.Count < maxReads; depth++)
{
var found = false;
foreach (var family in families)
{
if (depth >= family.Length)
continue;
found = true;
result.Add(family[depth]);
if (result.Count == maxReads)
break;
}

if (!found)
break;
}

return result.ToArray();
}

private static string RcbReadSchedulingFamily(string? name)
{
var value = name ?? string.Empty;
var stop = value.Length;
while (stop > 0 && value[stop - 1] >= '0' && value[stop - 1] <= '9')
stop--;
return stop == 0 ? value : value[..stop];
}

/// <summary>
/// Selects the live domain set independently from any SCL hint. This is important:
/// SCL may prioritize online work, but it must never manufacture or suppress live
Expand Down
67 changes: 67 additions & 0 deletions tests/AR.Iec61850.Tests/Mms/MmsSmartDiscoveryPolicyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,73 @@ public void ReportEnrichment_UsesOnlyNegotiatedWindowAndFiniteCandidateCount(
effectiveWindow, candidates));
}

[Fact]
public void ReportEnrichment_LargeIndexedCatalog_AdmitsEveryLiveFamilyWithin64Reads()
{
// Synthetic 35 families × 16 separately observed client slots. The
// former sorted Take(64) inspected only 4 families. Selection is a
// read-only scheduling hint; DatSet identity is still MMS Read proof.
var observed = Enumerable.Range(1, 35).SelectMany(family =>
Enumerable.Range(1, 16).Select(slot =>
ObservedRcb("IEDLD0", true, $"brcbFamily{family:D2}x{slot:D2}")))
.Reverse().ToArray();
var selected = MmsSmartDiscoveryPolicy.SelectReportEnrichmentCandidates(observed, 64);

Assert.Equal(64, selected.Length);
Assert.Equal(64, selected.Select(rcb => rcb.Reference).Distinct(StringComparer.Ordinal).Count());
Assert.Equal(35, selected.Select(rcb => rcb.Name[..^2]).Distinct(StringComparer.Ordinal).Count());
Assert.All(selected, rcb => Assert.Contains(observed, original =>
ReferenceEquals(original, rcb)));
}

[Fact]
public void ReportEnrichment_FairnessPreservesDomainsFcAndExactInstances()
{
var source = new[]
{
ObservedRcb("LD0", true, "Events01"),
ObservedRcb("LD0", true, "Events02"),
ObservedRcb("LD0", true, "Alarms01"),
ObservedRcb("LD1", true, "Events01"),
ObservedRcb("LD0", false, "Events01"),
ObservedRcb("LD0", false, "Events02")
};
var selected = MmsSmartDiscoveryPolicy.SelectReportEnrichmentCandidates(source.Reverse(), 5);
var selectedAgain = MmsSmartDiscoveryPolicy.SelectReportEnrichmentCandidates(source, 5);

Assert.Equal(selected.Select(x => x.Reference), selectedAgain.Select(x => x.Reference));
Assert.Equal(5, selected.Length);
Assert.Contains(selected, x => x.Reference == "LD0/LLN0.BR.Alarms01");
Assert.Contains(selected, x => x.Reference == "LD0/LLN0.RP.Events01");
Assert.Contains(selected, x => x.Reference == "LD1/LLN0.BR.Events01");
Assert.DoesNotContain(selected, x => x.Name == "Events03");
}

[Fact]
public void ReportEnrichment_BoundsAndDuplicatesFailClosed()
{
var source = new[]
{
ObservedRcb("LD0", true, "Events01"),
ObservedRcb("LD0", true, "Events01"),
ObservedRcb("LD0", true, "Events02")
};
Assert.Empty(MmsSmartDiscoveryPolicy.SelectReportEnrichmentCandidates(source, 0));
Assert.Single(MmsSmartDiscoveryPolicy.SelectReportEnrichmentCandidates(source, 1));
Assert.Equal(2, MmsSmartDiscoveryPolicy.SelectReportEnrichmentCandidates(source, 100).Length);
}

private static MmsReportControlCandidate ObservedRcb(string domain, bool buffered, string name)
=> new()
{
Domain = domain,
LogicalNode = "LLN0",
FunctionalConstraint = buffered ? "BR" : "RP",
Name = name,
Buffered = buffered,
Reference = $"{domain}/LLN0.{(buffered ? "BR" : "RP")}.{name}"
};

[Fact]
public void ReportEnrichment_PreservesExactSequentialPerRcbFieldsAndKpiCapture()
{
Expand Down
Loading