fix(opcuaclient): #1039 subscribe-time refusals ride the skipped-tag report (SkippedTagLedger.Append/Withdraw); probe preflight keeps an IPv6 zone

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 15:20:27 -05:00
parent d8cf9723d1
commit eff2b8e573
7 changed files with 287 additions and 6 deletions
+4 -2
View File
@@ -436,8 +436,10 @@ initialise (the AdminUI form drops them on the next save). Pinned by
> resolve to an upstream node id (`BadNodeIdInvalid`, no wire call) or the server refused the create (`BadNodeIdUnknown`,
> `BadAttributeIdInvalid`, … — `CreateItemsAsync` reports these on the item's status, it does not throw) — is published
> **Bad once with that code** and counted in ONE summarised Warning (G-12); it used to sit silently at the host's last
> stamp, `BadNoCommunication`, pointing at comms rather than the address. (It is not added to the skipped-tag report, which
> is an init-time snapshot.) The recovery / reconcile re-publish finds a ref's subscriptions through a per-subscription ref
> stamp, `BadNoCommunication`, pointing at comms rather than the address. (#1039: it is also appended to the skipped-tag
> report through `SkippedTagLedger.Append` — once per path however often the subscribe is retried, withdrawn by a later
> subscribe that gets the item, and cleared by the next re-initialise's rebuild, which re-appends what is still refused.
> The TCP preflight of Test Connect dials `Uri.IdnHost`, so a zone-qualified IPv6 endpoint keeps its zone.) The recovery / reconcile re-publish finds a ref's subscriptions through a per-subscription ref
> set, not a scan of every monitored item under the delivery lock (G-10: 20k refs went from ~6 s to ~1 s). `UnsubscribeAsync` /
> `UnsubscribeAlarmsAsync` leave the subscription tracked until they hold the subscription gate; if the wait is **cancelled**
> (the host's 5 s unsubscribe token vs a slow `ConditionRefresh`), the handlers are detached synchronously — nothing more is
@@ -124,6 +124,16 @@ public sealed class SkippedTagLedger
private int _stagedAuthored;
private int _stagedSkipped;
private List<SkippedTag>? _stagedSample;
private HashSet<string>? _stagedPaths;
// What the VISIBLE report was built from, kept so a late Append / Withdraw can recompute it (#1039).
private int _builtAuthored;
private int _builtSkipped;
private List<SkippedTag> _builtSample = [];
private HashSet<string> _builtPaths = [];
/// <summary>Skips noticed AFTER the build (a subscribe-time refusal), in encounter order. Reset by every rebuild.</summary>
private readonly List<SkippedTag> _appended = [];
/// <summary>
/// Starts staging a new tag-table build. The visible snapshot is left alone until
@@ -137,6 +147,7 @@ public sealed class SkippedTagLedger
_stagedAuthored = authoredCount;
_stagedSkipped = 0;
_stagedSample = new List<SkippedTag>(Math.Min(authoredCount, MaxSample));
_stagedPaths = new HashSet<string>(StringComparer.Ordinal);
}
}
@@ -154,11 +165,75 @@ public sealed class SkippedTagLedger
{
if (_stagedSample is null) return;
_stagedSkipped++;
_stagedPaths?.Add(rawPath ?? "");
if (_stagedSample.Count < MaxSample)
_stagedSample.Add(new SkippedTag(rawPath ?? "", reason ?? ""));
}
}
/// <summary>
/// Records a skip that was only discovered AFTER the build, against the already-visible report (#1039) — e.g. the
/// upstream server refusing a monitored item at subscribe time. The build-time skips are authored-config
/// problems; this is the same operator signal for a tag that only fails once the driver dials the device. Idempotent
/// per raw path (a subscribe retried every health tick must not inflate the count); a path the build already
/// skipped is not counted twice. A no-op before the first <see cref="Commit"/> ("no answer yet" is never turned
/// into a report), and cleared by the next <see cref="BeginRebuild"/>/<see cref="Commit"/> — a re-initialise
/// re-subscribes and re-appends what is still refused.
/// </summary>
/// <param name="rawPath">The authored raw path that was refused.</param>
/// <param name="reason">Operator-facing reason; should name the offending status.</param>
/// <returns><see langword="true"/> when the report changed.</returns>
public bool Append(string rawPath, string reason)
{
lock (_gate)
{
if (_visible is null) return false;
rawPath ??= "";
if (_builtPaths.Contains(rawPath)) return false;
var existing = _appended.FindIndex(s => string.Equals(s.RawPath, rawPath, StringComparison.Ordinal));
if (existing >= 0)
{
if (_appended[existing].Reason == (reason ?? "")) return false;
_appended[existing] = new SkippedTag(rawPath, reason ?? "");
}
else
{
_appended.Add(new SkippedTag(rawPath, reason ?? ""));
}
Republish();
return true;
}
}
/// <summary>
/// Withdraws a skip recorded by <see cref="Append"/> — the ref now has its upstream item (a later subscribe
/// succeeded), so it must stop being reported. Build-time skips are never withdrawn.
/// </summary>
/// <param name="rawPath">The raw path that is no longer refused.</param>
/// <returns><see langword="true"/> when the report changed.</returns>
public bool Withdraw(string rawPath)
{
lock (_gate)
{
if (_appended.Count == 0) return false;
var removed = _appended.RemoveAll(s => string.Equals(s.RawPath, rawPath ?? "", StringComparison.Ordinal)) > 0;
if (removed) Republish();
return removed;
}
}
/// <summary>Rebuilds the visible report from the committed build + the appended skips. Caller holds the gate.</summary>
private void Republish()
{
var sample = new List<SkippedTag>(_builtSample);
foreach (var a in _appended)
{
if (sample.Count >= MaxSample) break;
sample.Add(a);
}
_visible = new SkippedTagReport(_builtAuthored, _builtSkipped + _appended.Count, sample);
}
/// <summary>
/// Publishes the staged build as the visible snapshot, atomically. A call with no staged build
/// is a no-op.
@@ -168,8 +243,14 @@ public sealed class SkippedTagLedger
lock (_gate)
{
if (_stagedSample is null) return;
_visible = new SkippedTagReport(_stagedAuthored, _stagedSkipped, _stagedSample);
_builtAuthored = _stagedAuthored;
_builtSkipped = _stagedSkipped;
_builtSample = _stagedSample;
_builtPaths = _stagedPaths ?? [];
_appended.Clear();
_visible = new SkippedTagReport(_stagedAuthored, _stagedSkipped, _builtSample);
_stagedSample = null;
_stagedPaths = null;
}
}
@@ -46,7 +46,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// type stays free of driver bookkeeping.
/// </summary>
/// <param name="map">The map just built from the live session.</param>
private void RecordSkippedTags(NamespaceMap map)
internal void RecordSkippedTags(NamespaceMap map)
{
var authored = _options.RawTags;
_skippedTags.BeginRebuild(authored.Count);
@@ -2128,6 +2128,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
foreach (var pair in itemHandlers)
if (RejectedMonitoredItemStatus(pair.Item) is { } refused)
rejected.Add(new RejectedItem(RefOf(pair.Item), refused, $"the server refused the monitored item (0x{refused:X8})"));
// #1039: a ref a LATER subscribe now serves stops being reported skipped (the report is re-asserted from the
// refusals of each subscribe, so a fixed upstream node drops off it).
if (rejected.Count == 0) { foreach (var fullRef in fullReferences) _skippedTags.Withdraw(fullRef); }
else
{
var refused = rejected.Select(r => r.Ref).ToHashSet(StringComparer.Ordinal);
foreach (var fullRef in fullReferences)
if (!refused.Contains(fullRef)) _skippedTags.Withdraw(fullRef);
}
}
}
@@ -2160,6 +2170,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
internal void ReportRejectedItems(ISubscriptionHandle handle, IReadOnlyList<RejectedItem> rejected)
{
var now = Clock.GetUtcNow().UtcDateTime;
// #1039: the same refusals ride the skipped-tag report (/hosts), so an operator sees them without the log.
foreach (var r in rejected) _skippedTags.Append(r.Ref, r.Why);
lock (_deliveryLock)
{
foreach (var r in rejected)
@@ -143,7 +143,7 @@ public sealed class OpcUaClientDriverProbe : IDriverProbe
DisableHiResClock = true,
};
private static (string host, int port, string endpointUrl) ExtractTarget(OpcUaClientDriverOptions opts)
internal static (string host, int port, string endpointUrl) ExtractTarget(OpcUaClientDriverOptions opts)
{
// EndpointUrls wins over the convenience EndpointUrl when both are set.
var endpointUrl = opts.EndpointUrls.FirstOrDefault()
@@ -154,7 +154,11 @@ public sealed class OpcUaClientDriverProbe : IDriverProbe
if (!Uri.TryCreate(endpointUrl, UriKind.Absolute, out var uri))
return (string.Empty, 0, string.Empty);
var host = uri.Host;
// IdnHost, not Host: Uri.Host drops an IPv6 zone index (#819), so a link-local endpoint was dialled zone-less and
// failed the preflight as "Connect failed" before any OPC UA traffic. IdnHost is what the SDK's own transport
// dials (and it carries no brackets, which Socket.ConnectAsync's host overload does not want). An RFC 6874 "%25"
// delimiter is normalised to the "%" the socket layer expects.
var host = uri.IdnHost.Replace("%25", "%", StringComparison.Ordinal);
var port = uri.IsDefaultPort ? 4840 : uri.Port;
return (host, port, endpointUrl);
}
@@ -235,4 +235,102 @@ public sealed class SkippedTagLedgerTests
await Task.WhenAll(writer, reader);
}
// ── #1039: skips discovered AFTER the build (a subscribe-time refusal) ────────────────────────────────────
private static SkippedTagLedger Built(int authored, params string[] skipped)
{
var ledger = new SkippedTagLedger();
ledger.BeginRebuild(authored);
foreach (var s in skipped) ledger.Skip(s, "build reason");
ledger.Commit();
return ledger;
}
/// <summary>An appended skip changes the visible report: the true count grows, the sample carries it, the denominator is unchanged.</summary>
[Fact]
public void Append_adds_a_late_skip_to_the_visible_report()
{
var ledger = Built(5, "a");
ledger.Append("b", "server refused 0x80340000").ShouldBeTrue();
var report = ledger.Snapshot()!;
report.AuthoredCount.ShouldBe(5);
report.SkippedCount.ShouldBe(2);
report.Sample.Select(s => (s.RawPath, s.Reason)).ShouldBe([("a", "build reason"), ("b", "server refused 0x80340000")]);
}
/// <summary>Idempotent per path (a retried subscribe), and a path the build already skipped is never double counted.</summary>
[Fact]
public void Append_is_idempotent_per_path_and_never_double_counts_a_build_skip()
{
var ledger = Built(5, "a");
ledger.Append("b", "why").ShouldBeTrue();
ledger.Append("b", "why").ShouldBeFalse("the same refusal again is not a change");
ledger.Append("a", "why").ShouldBeFalse("the build already reported this path");
ledger.Snapshot()!.SkippedCount.ShouldBe(2);
// A changed reason for an appended path replaces it rather than adding a second entry.
ledger.Append("b", "different why").ShouldBeTrue();
var report = ledger.Snapshot()!;
report.SkippedCount.ShouldBe(2);
report.Sample.Single(s => s.RawPath == "b").Reason.ShouldBe("different why");
}
/// <summary>The count stays exact past the cap; only the detail list is capped, build skips first.</summary>
[Fact]
public void Append_keeps_the_count_exact_and_the_sample_capped()
{
var ledger = Built(100, Enumerable.Range(0, SkippedTagLedger.MaxSample - 1).Select(i => $"b{i}").ToArray());
for (var i = 0; i < 10; i++) ledger.Append($"late{i}", "why");
var report = ledger.Snapshot()!;
report.SkippedCount.ShouldBe(SkippedTagLedger.MaxSample - 1 + 10);
report.Sample.Count.ShouldBe(SkippedTagLedger.MaxSample);
report.Sample[SkippedTagLedger.MaxSample - 1].RawPath.ShouldBe("late0");
}
/// <summary>Withdraw removes an appended skip (the ref is served now) but never a build-time one.</summary>
[Fact]
public void Withdraw_removes_only_appended_skips()
{
var ledger = Built(5, "a");
ledger.Append("b", "why");
ledger.Withdraw("b").ShouldBeTrue();
ledger.Withdraw("b").ShouldBeFalse();
ledger.Withdraw("a").ShouldBeFalse("a build-time skip is not the subscribe's to withdraw");
var report = ledger.Snapshot()!;
report.SkippedCount.ShouldBe(1);
report.Sample.ShouldHaveSingleItem().RawPath.ShouldBe("a");
}
/// <summary>A rebuild starts over: appended skips are dropped at commit, and an in-flight rebuild does not leak them early.</summary>
[Fact]
public void A_rebuild_clears_appended_skips_only_at_commit()
{
var ledger = Built(5, "a");
ledger.Append("b", "why");
ledger.BeginRebuild(5);
ledger.Snapshot()!.SkippedCount.ShouldBe(2, "the previous complete answer stands until the rebuild commits");
ledger.Commit();
ledger.Snapshot()!.SkippedCount.ShouldBe(0);
}
/// <summary>"No answer yet" is never turned into a report by a late skip.</summary>
[Fact]
public void Append_before_any_build_is_a_no_op()
{
var ledger = new SkippedTagLedger();
ledger.Append("x", "why").ShouldBeFalse();
ledger.Snapshot().ShouldBeNull();
}
}
@@ -189,4 +189,59 @@ public sealed class OpcUaClientDriverProbeTests
}
finally { listener.Stop(); }
}
// ── #1039: zone-qualified IPv6 hosts reach the preflight with their zone ───────────────────────
/// <summary>
/// The preflight dials the host <see cref="OpcUaClientDriverProbe.ExtractTarget"/> returns. .NET's
/// <see cref="Uri.Host"/> drops an IPv6 zone index (#819), so a link-local <c>fe80::1%eth0</c> endpoint was dialled
/// zone-less — unroutable, a false "Connect failed" before any OPC UA traffic. The host must carry the zone.
/// </summary>
[Theory]
[InlineData("opc.tcp://[fe80::1%eth0]:4841", "fe80::1%eth0", 4841)]
[InlineData("opc.tcp://[fe80::1%4]:4841/Ua", "fe80::1%4", 4841)]
// RFC 6874's encoded delimiter is accepted and normalised to the '%' the socket layer wants.
[InlineData("opc.tcp://[fe80::1%25eth0]:4841", "fe80::1%eth0", 4841)]
[InlineData("opc.tcp://[fe80::1%eth0]", "fe80::1%eth0", 4840)]
// Positive controls: a zone-less literal and a name are unchanged.
[InlineData("opc.tcp://[::1]:4841", "::1", 4841)]
[InlineData("opc.tcp://plc-host:4841", "plc-host", 4841)]
public void The_preflight_target_keeps_an_IPv6_zone_index(string endpointUrl, string expectedHost, int expectedPort)
{
var (host, port, url) = OpcUaClientDriverProbe.ExtractTarget(new OpcUaClientDriverOptions { EndpointUrl = endpointUrl });
host.ShouldBe(expectedHost);
port.ShouldBe(expectedPort);
url.ShouldBe(endpointUrl);
}
/// <summary>
/// End to end: a zone-qualified loopback literal reaches the preflight's socket connect (a listener that accepts
/// then closes proves it dialled), so the failure is the discovery handshake, never "Connect failed".
/// <c>::1%0</c> is a numeric zone that is valid everywhere an IPv6 socket is.
/// </summary>
[Fact]
public async Task A_zone_qualified_IPv6_literal_endpoint_passes_the_tcp_preflight()
{
if (!Socket.OSSupportsIPv6) Assert.Skip("IPv6 is not available on this host.");
var listener = new TcpListener(IPAddress.IPv6Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
var testCt = TestContext.Current.CancellationToken;
var accepted = Task.Run(async () =>
{
try { using var c = await listener.AcceptTcpClientAsync(testCt); return true; }
catch { return false; }
}, testCt);
try
{
var result = await _probe.ProbeAsync(
$$"""{"EndpointUrl":"opc.tcp://[::1%0]:{{port}}"}""", TimeSpan.FromSeconds(5), testCt);
result.Ok.ShouldBeFalse("the listener is not an OPC UA server");
result.Message.ShouldNotBeNull().ShouldNotContain("Connect failed", Case.Insensitive);
(await accepted.WaitAsync(TimeSpan.FromSeconds(5), testCt)).ShouldBeTrue("the preflight reached the listener");
}
finally { listener.Stop(); }
}
}
@@ -164,6 +164,35 @@ public sealed class OpcUaClientReview1202FindingsTests
log.Entries.Where(e => e.Level == LogLevel.Warning).ShouldHaveSingleItem().Message.ShouldContain("2 of the subscribed");
}
/// <summary>
/// #1039: the same refusals ride the skipped-tag report (so /hosts shows them without the log), once per path even
/// when the subscribe is retried; a re-initialise's rebuild clears them. Positive control: nothing is reported
/// before any refusal.
/// </summary>
[Fact]
public void Subscribe_time_refusals_are_added_to_the_skipped_tag_report_once_per_path()
{
var (drv, _) = NewConnectedDriver();
using var _ = drv;
drv.RecordSkippedTags(NamespaceMap.FromTable(new NamespaceTable(), Tags));
drv.GetSkippedTags().ShouldNotBeNull().SkippedCount.ShouldBe(0);
var handle = drv.AddSubscriptionForTest([SpeedRef]);
OpcUaClientDriver.RejectedItem[] refused =
[new("Plant/dev/Gone", 0x80340000u, "the server refused the monitored item (0x80340000)")];
drv.ReportRejectedItems(handle, refused);
drv.ReportRejectedItems(handle, refused); // the host retries the subscribe every health tick
var report = drv.GetSkippedTags().ShouldNotBeNull();
report.SkippedCount.ShouldBe(1);
report.Sample.ShouldHaveSingleItem().RawPath.ShouldBe("Plant/dev/Gone");
report.Sample[0].Reason.ShouldContain("refused");
report.AuthoredCount.ShouldBe(1);
drv.RecordSkippedTags(NamespaceMap.FromTable(new NamespaceTable(), Tags)); // re-initialise
drv.GetSkippedTags()!.SkippedCount.ShouldBe(0);
}
// ── G-13 ─────────────────────────────────────────────────────────────────────────────────────────────────────
private static readonly Dictionary<string, string> TripIndex = new() { ["ns=3;s=Alarms.Trip1"] = "Plant/opc/plc/Trip1" };