Merge branch 'master' into worktree-agent-a720278a57ae41792

Claude-Session: https://claude.ai/code/session_01GT67AD99zQQqpLCVm3p7xk
This commit is contained in:
Joseph Doherty
2026-11-11 13:25:58 -05:00
69 changed files with 6709 additions and 915 deletions
@@ -71,7 +71,7 @@ public abstract class QualityMixConformance : ConformanceBase
/// <summary>Hand-computed Part 13 DurationBad of Q's eight intervals, seconds.</summary>
private static readonly double[] QDurationBad = [3, 0, 0, 0, 5, 0, 0, 3];
/// <summary>What the 1.5.378.182 baseline answers for Q's PercentGood (Uncertain counted as Good, #796).</summary>
/// <summary>What the untouched 1.5.378.182 baseline answers for Q's PercentGood (Uncertain counted as Good, #796; live before #809).</summary>
private static readonly double[] QBaselinePercentGood = [70, 100, 100, 100, 50, 100, 100, 70];
/// <summary>
@@ -182,7 +182,8 @@ public abstract class QualityMixConformance : ConformanceBase
var pGood = (await src.ReadProcessedAsync("Q", At(0), At(80), Ten, HistoryAggregateType.PercentGood, Ct)).Samples;
ShouldBeClose(Values(good), Values(pGood).Select(p => p * Ten.TotalMilliseconds / 100).ToArray(), "DurationGood vs PercentGood");
// The baseline (the live AggregateFilter calculator, #809) answers Q's DurationGood with the Uncertain time added.
// The untouched baseline (the live AggregateFilter calculator before #809) answers Q's DurationGood with the
// Uncertain time added; the live calculator now answers the Part 13 values above (SdkAggregateParityTests).
var baseline = SdkAggregateOracle.RunSdkAsIs(HistoryAggregateType.DurationGood, At(0), At(80), Ten,
Q.Select(r => (r.T, r.V, r.Status)));
ShouldBeClose(baseline.Select(r => Convert.ToDouble(r.Value)).ToArray(),
@@ -236,15 +237,16 @@ public abstract class QualityMixConformance : ConformanceBase
public async Task Processed_reads_over_partial_data_match_the_Part_13_oracle(double from, double to, double intervalS)
{
// QP's start-of-data and end-of-data intervals against the oracle, forward and reverse (#821). Left out, each a documented or pinned divergence:
// TimeAverage2 / Total2 (the SDK's 1 ms end-of-data region), the min/max family (the SDK sets Partial on a Bad
// result), and TimeAverage / Total (pinned by Time_weighted_values_over_partial_data_cover_only_the_data below).
// TimeAverage2 / Total2 (the SDK's 1 ms end-of-data region) and the min/max family (the SDK sets Partial on a Bad
// result). TimeAverage / Total are in since #821: the live calculator no longer integrates the span before QP's
// Uncertain first sample (the hand-computed values are pinned below as well).
await B.SeedAsync("QP", QP);
await AssertMatchesOracle("QP", Rounded(QP), from, to, intervalS,
[
HistoryAggregateType.PercentGood, HistoryAggregateType.PercentBad, HistoryAggregateType.DurationGood,
HistoryAggregateType.DurationBad, HistoryAggregateType.Count,
HistoryAggregateType.Average, HistoryAggregateType.Start, HistoryAggregateType.End, HistoryAggregateType.Delta,
HistoryAggregateType.Interpolative,
HistoryAggregateType.Interpolative, HistoryAggregateType.TimeAverage, HistoryAggregateType.Total,
]);
}
@@ -254,9 +256,9 @@ public abstract class QualityMixConformance : ConformanceBase
// Part 13 §5.4.3.3/§5.4.3.8 over QP's [0,20) (data from +5): the interpolated-bounding signal is defined from +5
// only — 10 → 11 over [5,12) (area 73.5) and 11 → 11 + 8/13 over [12,20) (area 4·(22 + 8/13)) — so
// Total = 73.5 + 88 + 32/13 and TimeAverage = Total ÷ 15 s; Uncertain (an Uncertain value used, not fully covered),
// Partial (the data starts inside). Divergence found by #810: the 1.5.378.182 baseline, whose first sample is
// Uncertain here, integrates the uncovered [0,5) as a ramp from 0 (Total +25) — so these are pinned by hand, not
// against the oracle.
// Partial (the data starts inside). Found by #810: the untouched 1.5.378.182 baseline, whose first sample is
// Uncertain here, integrates the uncovered [0,5) as a ramp from 0 (Total +25); since #821 the live calculator (the
// oracle) does not.
await B.SeedAsync("QP", QP);
var src = B.CreateDataSource();
const double total = 73.5 + 88 + 32d / 13;
@@ -267,8 +269,10 @@ public abstract class QualityMixConformance : ConformanceBase
((double)avg.Value!).ShouldBe(total / 15, 1e-6);
avg.StatusCode.ShouldBe(UncertainCalc | Partial);
var sdk = SdkAggregateOracle.Run(HistoryAggregateType.Total, B.Round(At(0)), B.Round(At(20)), Twenty, Rounded(QP)).Single();
Convert.ToDouble(sdk.Value).ShouldBe(total + 25, 1e-6, "baseline divergence — if this moves, compare QP's TimeAverage/Total to the oracle");
var live = SdkAggregateOracle.Run(HistoryAggregateType.Total, B.Round(At(0)), B.Round(At(20)), Twenty, Rounded(QP)).Single();
Convert.ToDouble(live.Value).ShouldBe(total, 1e-6, "live AggregateFilter equals HistoryRead (#821)");
var before = SdkAggregateOracle.RunSdkAsIs(HistoryAggregateType.Total, B.Round(At(0)), B.Round(At(20)), Twenty, Rounded(QP)).Single();
Convert.ToDouble(before.Value).ShouldBe(total + 25, 1e-6, "the untouched baseline (live before #821)");
}
[Fact]
@@ -276,8 +280,8 @@ public abstract class QualityMixConformance : ConformanceBase
{
// #821: the reverse-order variant of the late-start case above — (0,20] read 20 → 0. The same Part 13 integral and
// average over the covered [5,20); Uncertain; NOT Partial (a reverse read keys start-of-data on the latest sample,
// which is past the window — the SDK's rule, SdkAggregateParityTests); stamped with the later edge (#677). The
// baseline's reverse answer carries the same +25 ramp divergence.
// which is past the window — the SDK's rule, SdkAggregateParityTests); stamped with the later edge (#677). The live
// calculator agrees since #821; the untouched baseline's reverse answer carries the same +25 ramp.
await B.SeedAsync("QP", QP);
var src = B.CreateDataSource();
const double total = 73.5 + 88 + 32d / 13;
@@ -289,8 +293,10 @@ public abstract class QualityMixConformance : ConformanceBase
((double)avg.Value!).ShouldBe(total / 15, 1e-6);
avg.StatusCode.ShouldBe(UncertainCalc);
var sdk = SdkAggregateOracle.Run(HistoryAggregateType.Total, B.Round(At(20)), B.Round(At(0)), Twenty, Rounded(QP)).Single();
Convert.ToDouble(sdk.Value).ShouldBe(total + 25, 1e-6, "baseline divergence (reverse) — #821");
var live = SdkAggregateOracle.Run(HistoryAggregateType.Total, B.Round(At(20)), B.Round(At(0)), Twenty, Rounded(QP)).Single();
Convert.ToDouble(live.Value).ShouldBe(total, 1e-6, "live AggregateFilter equals HistoryRead (reverse) — #821");
var before = SdkAggregateOracle.RunSdkAsIs(HistoryAggregateType.Total, B.Round(At(20)), B.Round(At(0)), Twenty, Rounded(QP)).Single();
Convert.ToDouble(before.Value).ShouldBe(total + 25, 1e-6, "the untouched baseline (live before #821, reverse)");
}
private async Task AssertMatchesOracle(string tag, (DateTime, HistorianValue, uint)[] rows, double from, double to,
@@ -2,7 +2,7 @@ using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Compatibility.Aggregates;
using BaselineAggregateCalculator = ZB.MOM.WW.OtOpcUa.OpcUaServer.Compatibility.Aggregates.AggregateCalculator;
using BaselineStatusAggregateCalculator = ZB.MOM.WW.OtOpcUa.OpcUaServer.Compatibility.Aggregates.StatusAggregateCalculator;
using BaselineAggregators = ZB.MOM.WW.OtOpcUa.OpcUaServer.Compatibility.Aggregates.Aggregators;
using Shouldly;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
@@ -18,17 +18,25 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Conformance;
/// <remarks>
/// <para>Shared (source-linked) by <c>Sql.Common.Tests</c> and both SQL backends' integration suites.</para>
/// <para>
/// <b>PercentGood (and, since #820, DurationGood) are the aggregates not taken as-is (#796).</b> The 1.5.378.182 baseline changed
/// <b>PercentGood / DurationGood (#796, #820, #809).</b> The 1.5.378.182 baseline changed
/// <c>StatusAggregateCalculator.ComputeDurationGoodBad</c> (1.5.378.106 and earlier counted Good regions only):
/// with TreatUncertainAsBad = false it counts Uncertain regions as <b>Good</b> time (as Bad when true). Part 13
/// keeps Uncertain out of both (§5.4.3.31 DurationGood counts Good regions; §5.4.3.33 PercentGood =
/// DurationGood ÷ interval; Mantis 0006166, closed "no change required": an all-Uncertain interval is
/// PercentGood 0 <i>and</i> PercentBad 0), and so does ours. <see cref="Run"/> therefore answers PercentGood
/// (and DurationGood) through <see cref="Part13GoodCalculator"/>: the SAME baseline calculator, region machinery (simple
/// bounds, end-of-data 1 ms region, status and Partial bits) and server-default configuration, counting only
/// Good regions — exactly what the pre-.182 oracle computed. PercentBad / DurationBad still count Bad regions only
/// (unchanged by .182) and are compared as-is. <see cref="RunSdkAsIs"/> runs the baseline untouched, for the test that pins
/// the divergence.
/// PercentGood 0 <i>and</i> PercentBad 0), and so does ours. Since #809 the LIVE calculators follow Part 13 too:
/// <c>CompatibilityAggregateFactory</c> serves those two through the application's
/// <c>GoodOnlyStatusAggregateCalculator</c> (the same baseline region machinery — simple bounds, end-of-data 1 ms
/// region, status and Partial bits — counting only Good regions), so <see cref="Run"/> / <see cref="RunLive"/> are
/// exactly what a live AggregateFilter computes, for every aggregate. PercentBad / DurationBad count Bad regions only
/// (unchanged by .182). <see cref="RunSdkAsIs"/> runs the untouched baseline (what live served before #809 / #821),
/// for the tests that pin those divergences.
/// </para>
/// <para>
/// <b>TimeAverage / Total with no start bound (#821).</b> When the data starts inside an interval with an
/// <b>Uncertain</b> first value, the baseline integrates the uncovered span before it as a ramp from 0 (its region
/// machinery overwrites that region's Bad status with Uncertain). Part 13 ("No Start Bound: Calculate Partial
/// Interval") and ours integrate only the covered part, as the baseline itself does after a Good first value. Since
/// #821 the live calculators follow Part 13 here too (<c>CoveredTimeAverageAggregateCalculator</c>).
/// </para>
/// <para>
/// Not <c>100 − PercentBad</c> under TreatUncertainAsBad = true: that flag also changes the region machinery
@@ -54,8 +62,9 @@ public static class SdkAggregateOracle
};
/// <summary>
/// Runs the Part 13 oracle for <paramref name="aggregate"/> over <paramref name="samples"/>: the baseline calculator,
/// except PercentGood / DurationGood, which count Good regions only (see the remarks, #796/#820).
/// Runs the Part 13 oracle for <paramref name="aggregate"/> over <paramref name="samples"/>: the live calculator
/// (<see cref="RunLive"/>) — the baseline, except PercentGood / DurationGood, which count Good regions only, and
/// TimeAverage / Total, which leave the span before an Uncertain first value out (see the remarks, #796/#820/#809/#821).
/// </summary>
/// <param name="aggregate">The aggregate.</param>
/// <param name="start">Request start (later than <paramref name="end"/> for a reverse read).</param>
@@ -65,16 +74,31 @@ public static class SdkAggregateOracle
/// <returns>The oracle's processed values, in the order it returns them.</returns>
public static IReadOnlyList<Result> Run(HistoryAggregateType aggregate, DateTime start, DateTime end, TimeSpan interval,
IEnumerable<(DateTime Time, HistorianValue Value, uint Status)> samples) =>
aggregate is HistoryAggregateType.PercentGood or HistoryAggregateType.DurationGood
? RunCore(new LegacyCalculatorAdapter(new Part13GoodCalculator(AggregateId(aggregate),
start, end, interval.TotalMilliseconds, false, DefaultConfiguration, Telemetry,
usePercent: aggregate == HistoryAggregateType.PercentGood)), start, end, samples)
: RunSdkAsIs(aggregate, start, end, interval, samples);
RunLive(aggregate, start, end, interval, samples);
/// <summary>
/// Runs the baseline (1.5.378.182) calculator for <paramref name="aggregate"/> exactly as it computes it, under
/// <see cref="DefaultConfiguration"/> — including its PercentGood rule (Uncertain counted as Good) that
/// <see cref="Run"/> deliberately does not use (#796).
/// Runs exactly the calculator the server registers for live AggregateFilter monitored items
/// (<c>CompatibilityAggregateFactory.Create</c>, the #809 Good-only PercentGood / DurationGood and the #821
/// covered-only TimeAverage / Total included).
/// </summary>
/// <param name="aggregate">The aggregate.</param>
/// <param name="start">Request start (later than <paramref name="end"/> for a reverse read).</param>
/// <param name="end">Request end.</param>
/// <param name="interval">Processing interval.</param>
/// <param name="samples">Every stored sample of the tag, any order (sorted here).</param>
/// <param name="configuration">The configuration (default <see cref="DefaultConfiguration"/>).</param>
/// <returns>The calculator's processed values, in the order it returns them.</returns>
public static IReadOnlyList<Result> RunLive(HistoryAggregateType aggregate, DateTime start, DateTime end,
TimeSpan interval, IEnumerable<(DateTime Time, HistorianValue Value, uint Status)> samples,
AggregateConfiguration? configuration = null) =>
RunCore(CompatibilityAggregateFactory.Create(AggregateId(aggregate), start, end, interval.TotalMilliseconds, false,
configuration ?? DefaultConfiguration, Telemetry), start, end, samples);
/// <summary>
/// Runs the untouched baseline (1.5.378.182) calculator for <paramref name="aggregate"/> exactly as it computes it,
/// under <see cref="DefaultConfiguration"/> — including its PercentGood / DurationGood rule (Uncertain counted as
/// Good) and its TimeAverage / Total ramp before an Uncertain first value, which neither HistoryRead nor, since
/// #809 / #821, the live calculators use.
/// </summary>
/// <param name="aggregate">The aggregate.</param>
/// <param name="start">Request start (later than <paramref name="end"/> for a reverse read).</param>
@@ -86,8 +110,9 @@ public static class SdkAggregateOracle
public static IReadOnlyList<Result> RunSdkAsIs(HistoryAggregateType aggregate, DateTime start, DateTime end,
TimeSpan interval, IEnumerable<(DateTime Time, HistorianValue Value, uint Status)> samples,
AggregateConfiguration? configuration = null) =>
RunCore(CompatibilityAggregateFactory.Create(AggregateId(aggregate), start, end, interval.TotalMilliseconds, false,
configuration ?? DefaultConfiguration, Telemetry), start, end, samples);
RunCore(new LegacyCalculatorAdapter(BaselineAggregators.CreateStandardCalculator(AggregateId(aggregate), start, end,
interval.TotalMilliseconds, false, configuration ?? DefaultConfiguration, Telemetry)
?? throw new ArgumentOutOfRangeException(nameof(aggregate))), start, end, samples);
private static IReadOnlyList<Result> RunCore(IAggregateCalculator calc, DateTime start, DateTime end,
IEnumerable<(DateTime Time, HistorianValue Value, uint Status)> samples)
@@ -155,42 +180,7 @@ public static class SdkAggregateOracle
problems.ShouldBeEmpty($"{label} differs from the SDK:\n" + string.Join("\n", problems));
}
/// <summary>
/// The baseline <see cref="BaselineStatusAggregateCalculator"/> with PercentGood / DurationGood counting <b>Good</b>
/// regions only — Part 13 §5.4.3.31/§5.4.3.33, and the 1.5.378.106 rule. Everything else (bounds, regions, Partial,
/// status, the millisecond Duration unit) is the baseline's own code, run under the same configuration as
/// PercentBad / DurationBad.
/// </summary>
private sealed class Part13GoodCalculator(NodeId aggregateId, DateTime startTime, DateTime endTime,
double processingInterval, bool stepped, AggregateConfiguration configuration, ITelemetryContext telemetry,
bool usePercent)
: BaselineStatusAggregateCalculator(aggregateId, startTime, endTime, processingInterval, stepped, configuration, telemetry)
{
protected override LegacyDataValue ComputeValue(TimeSlice slice)
{
var values = GetValuesWithSimpleBounds(slice);
if (values == null || values.Count == 0) return GetNoDataValue(slice);
var regions = GetRegionsInValueSet(values, false, true);
double good = 0, total = 0;
foreach (var region in regions)
{
total += region.Duration;
if (StatusCode.IsGood(region.StatusCode)) good += region.Duration;
}
var value = new LegacyDataValue
{
WrappedValue = ZB.MOM.WW.OtOpcUa.OpcUaServer.SdkValueBoundary.FromClr(usePercent ? good / total * 100 : good),
SourceTimestamp = GetTimestamp(slice),
ServerTimestamp = GetTimestamp(slice),
};
value.StatusCode = value.StatusCode.WithAggregateBits(AggregateBits.Calculated);
return value;
}
}
/// <summary>The <see cref="CompatibilityAggregateFactory"/> adapter, for a calculator built here.</summary>
/// <summary>The <see cref="CompatibilityAggregateFactory"/> adapter, for a baseline calculator built here.</summary>
private sealed class LegacyCalculatorAdapter(BaselineAggregateCalculator calculator) : IAggregateCalculator
{
public NodeId AggregateId => calculator.AggregateId;
@@ -15,33 +15,99 @@ public sealed class GatewayGalaxyPlatformSourceTests
return o;
}
/// <summary>Every request carries the platform template filter, no attributes, and the page size; replies are re-filtered.</summary>
[Fact]
public async Task Requests_filter_on_platform_templates_without_attributes_and_replies_are_refiltered()
/// <summary>
/// A fake gateway that applies the request filters with the SAME semantics as the shared
/// <c>GalaxyHierarchyProjector.MatchesFilters</c>: every <c>template_chain_contains</c> token must
/// match (AND, case-insensitive substring over the chain), <c>category_ids</c> is an OR set. Pages
/// the filtered result at the request's page size.
/// </summary>
private sealed class FilteringGateway(params GalaxyObject[] galaxy)
{
var requests = new List<DiscoverHierarchyRequest>();
Task<DiscoverHierarchyReply> Discover(DiscoverHierarchyRequest req, CancellationToken ct)
public List<DiscoverHierarchyRequest> Requests { get; } = [];
public Task<DiscoverHierarchyReply> Discover(DiscoverHierarchyRequest req, CancellationToken ct)
{
requests.Add(req);
Requests.Add(req.Clone());
var matched = galaxy.Where(o => Matches(o, req)).ToList();
var offset = req.PageToken == "" ? 0 : int.Parse(req.PageToken.Split(':')[1]);
var reply = new DiscoverHierarchyReply();
if (req.PageToken == "")
reply.Objects.Add(matched.Skip(offset).Take(req.PageSize));
if (offset + req.PageSize < matched.Count)
{
reply.Objects.Add([Obj("Plat01", "$WinPlatform"), Obj("Tank01", "$UserDefined")]);
reply.NextPageToken = "p2";
}
else
{
reply.Objects.Add([Obj("Eng01", "$AppEngine", "$WinPlatform"), Obj("Plat01", "$WinPlatform"), Obj("", "$WinPlatform")]);
reply.NextPageToken = $"{string.Join(",", req.TemplateChainContains)}:{offset + req.PageSize}";
}
return Task.FromResult(reply);
}
var names = await GatewayGalaxyPlatformSource.QueryAsync(Discover, pageSize: 50, CancellationToken.None);
private static bool Matches(GalaxyObject obj, DiscoverHierarchyRequest req)
{
if (req.CategoryIds.Count > 0 && !req.CategoryIds.Contains(obj.CategoryId)) return false;
foreach (var filter in req.TemplateChainContains)
{
if (!obj.TemplateChain.Any(t => t.Contains(filter, StringComparison.OrdinalIgnoreCase))) return false;
}
return true;
}
}
names.ShouldBe(["Plat01", "Eng01"]);
requests.Count.ShouldBe(2);
requests.ShouldAllBe(r => r.PageSize == 50 && r.IncludeAttributes == false);
requests.ShouldAllBe(r => r.TemplateChainContains.Contains("$WinPlatform") && r.TemplateChainContains.Contains("$AppEngine"));
/// <summary>
/// #864: against a gateway that ANDs template filters (as the real one does), every deployed
/// <c>$WinPlatform</c> AND every <c>$AppEngine</c> is found — the old single request carrying both
/// tokens matched none. Shape of the VD03 DEV galaxy: 3 platforms, 2 engines.
/// </summary>
[Fact]
public async Task Finds_every_platform_and_engine_against_an_AND_filtering_gateway()
{
var gw = new FilteringGateway(
Obj("CTRX_DEV", "$WinPlatform"),
Obj("DevWinPlatform", "$WinPlatform"),
Obj("JoePlatform", "$JoePlatformTemplate", "$WinPlatform"),
Obj("DevAppEngine", "$AppEngine"),
Obj("JoeAppEngine", "$AppEngine"),
Obj("Tank01", "$UserDefined"),
Obj("Area01", "$Area"));
var names = await GatewayGalaxyPlatformSource.QueryAsync(gw.Discover, pageSize: 50, CancellationToken.None);
names.ShouldBe(["CTRX_DEV", "DevWinPlatform", "JoePlatform", "DevAppEngine", "JoeAppEngine"]);
gw.Requests.ShouldAllBe(r => r.TemplateChainContains.Count == 1 && r.PageSize == 50 && r.IncludeAttributes == false);
gw.Requests.Select(r => r.TemplateChainContains[0]).Distinct().ShouldBe(["$WinPlatform", "$AppEngine"]);
}
/// <summary>Each per-template sweep pages to completion independently; tag names are de-duplicated across sweeps.</summary>
[Fact]
public async Task Each_template_sweep_pages_independently_and_names_are_deduplicated()
{
var gw = new FilteringGateway(
Obj("Plat01", "$WinPlatform"),
Obj("Plat02", "$WinPlatform"),
Obj("Plat03", "$WinPlatform"),
// An object whose chain carries both templates is reported once.
Obj("Hybrid01", "$AppEngine", "$WinPlatform"),
Obj("Eng01", "$AppEngine"),
Obj("Eng02", "$AppEngine"),
Obj("", "$WinPlatform"));
var names = await GatewayGalaxyPlatformSource.QueryAsync(gw.Discover, pageSize: 2, CancellationToken.None);
names.ShouldBe(["Plat01", "Plat02", "Plat03", "Hybrid01", "Eng01", "Eng02"]);
// $WinPlatform: 5 matches (incl. the empty tag) => 3 pages; $AppEngine: 3 matches => 2 pages.
gw.Requests.Count(r => r.TemplateChainContains[0] == "$WinPlatform").ShouldBe(3);
gw.Requests.Count(r => r.TemplateChainContains[0] == "$AppEngine").ShouldBe(2);
}
/// <summary>A gateway that ignores the filter still yields only platforms (replies are re-filtered on the chain).</summary>
[Fact]
public async Task Replies_are_refiltered_on_the_template_chain()
{
Task<DiscoverHierarchyReply> Discover(DiscoverHierarchyRequest req, CancellationToken ct)
{
var reply = new DiscoverHierarchyReply();
reply.Objects.Add([Obj("Plat01", "$WinPlatform"), Obj("Tank01", "$UserDefined"), Obj("Eng01", "$AppEngine")]);
return Task.FromResult(reply);
}
(await GatewayGalaxyPlatformSource.QueryAsync(Discover, pageSize: 50, CancellationToken.None)).ShouldBe(["Plat01", "Eng01"]);
}
/// <summary>A gateway that strips the template chain is trusted to have filtered server-side.</summary>
@@ -844,6 +844,7 @@ public sealed class EarlyEventWindowTests
"g", Opts(), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber)
{
RecreateOverrideForTests = _ => Task.CompletedTask,
StreamRequestWait = TimeSpan.FromMilliseconds(100), // advises in the reopen window on purpose (#865 bound)
};
var delivered = new ConcurrentQueue<(string Ref, double Value)>();
driver.OnDataChange += (_, e) => delivered.Enqueue((e.FullReference, (double)e.Snapshot.Value!));
@@ -897,6 +898,31 @@ public sealed class EarlyEventWindowTests
driver.SubscriptionsForTests.ResolveSubscribers(77).ShouldBeEmpty();
}
/// <summary>
/// #865 stress finding: the dispatch fast path looked the handle up, then checked for an open window —
/// not atomically. A subscribe that registered the handle AND closed its window in between made the
/// event "stale" and its initial value was dropped for good. It must resolve.
/// </summary>
[Fact]
public void A_registration_landing_between_the_fast_path_lookup_and_the_window_check_still_resolves()
{
var registry = new SubscriptionRegistry();
var session = registry.CurrentSession;
var window = registry.BeginPendingSubscribe();
registry.AfterFastPathMissForTests = () =>
{
registry.AfterFastPathMissForTests = null;
registry.TryRegister(registry.NextSubscriptionId(), [new TagBinding("Tank.A", 7)], session).ShouldBeTrue();
window.Dispose(); // the subscribe's window closes right after its registration
};
registry.ResolveOrPark(DataChange(7, 1), session, out var subscribers, out _).ShouldBe(EarlyEventOutcome.Resolved);
subscribers.Single().FullReference.ShouldBe("Tank.A");
// Positive control for the Stale branch: an unknown handle with no window open is still dropped.
registry.ResolveOrPark(DataChange(8, 1), session, out _, out _).ShouldBe(EarlyEventOutcome.Stale);
}
/// <summary>I-B: a purge that completes after a reconnect does not delete the new session's parked values.</summary>
[Fact]
public void A_purge_for_an_older_session_is_a_no_op()
@@ -1027,6 +1053,9 @@ public sealed class EarlyEventWindowTests
"g", Opts(), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber)
{
RecreateOverrideForTests = _ => Task.CompletedTask,
// These tests advise in the reopen → replay window on purpose (fencing, not values). #865 makes
// such an advise wait for the replay's pump, bounded; keep the bound short so they don't idle.
StreamRequestWait = TimeSpan.FromMilliseconds(100),
};
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
return driver;
@@ -0,0 +1,62 @@
using System.Runtime.CompilerServices;
using Shouldly;
using Xunit;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// <summary>
/// #865: <see cref="EventPump.StreamRequested"/> — what advise paths wait on so an initial value is
/// never pushed before the stream is requested. It must complete once the RPC is started (before any
/// event), and must never strand a waiter on a pump whose loop died before getting that far.
/// </summary>
public sealed class EventPumpStreamRequestedTests
{
private sealed class ScriptedSubscriber(Func<CancellationToken, IAsyncEnumerable<MxEvent>> stream) : IGalaxySubscriber
{
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
=> Task.FromResult<IReadOnlyList<SubscribeResult>>([]);
public Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken) => Task.CompletedTask;
public IAsyncEnumerable<MxEvent> StreamEventsAsync(CancellationToken cancellationToken) => stream(cancellationToken);
}
/// <summary>A stream that is requested and then never yields: StreamRequested completes; the RPC started first.</summary>
[Fact]
public async Task Completes_once_the_stream_is_requested_before_any_event()
{
var rpcStarted = 0;
async IAsyncEnumerable<MxEvent> Never([EnumeratorCancellation] CancellationToken ct)
{
Interlocked.Exchange(ref rpcStarted, 1); // the synchronous first step — where a real call is created
await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
yield break;
}
await using var pump = new EventPump(new ScriptedSubscriber(Never), new SubscriptionRegistry());
pump.StreamRequested.IsCompleted.ShouldBeFalse("not before Start");
pump.Start();
await TestWait.ForAsync(pump.StreamRequested, "StreamRequested must complete once the stream call is started");
Volatile.Read(ref rpcStarted).ShouldBe(1, "StreamRequested must not precede the stream call");
}
/// <summary>A subscriber that throws before reaching the RPC still completes StreamRequested (no stranded waiter).</summary>
[Fact]
public async Task Completes_when_the_stream_fails_before_the_rpc()
{
var faulted = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
await using var pump = new EventPump(
new ScriptedSubscriber(_ => throw new InvalidOperationException("not connected")),
new SubscriptionRegistry(),
onStreamFault: ex => faulted.TrySetResult(ex));
pump.Start();
await TestWait.ForAsync(pump.StreamRequested, "a dead pump must not strand a StreamRequested waiter");
(await TestWait.ForAsync(faulted.Task, "positive control: the failure is still reported as a stream fault"))
.ShouldBeOfType<InvalidOperationException>();
}
}
@@ -272,7 +272,10 @@ public sealed class GalaxyDriverFixRound1Tests
[Fact]
public async Task Production_path_queries_the_platform_source_at_init()
{
var platforms = new ScriptedPlatformSource();
// An empty galaxy: since #865 a probe advise starts the event stream first, and this owned runtime's
// gRPC channel points at no real gateway — its stream would fault and (correctly) degrade health.
// The query itself is what this test pins.
var platforms = new ScriptedPlatformSource { Script = _ => [] };
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, platformSource: platforms)
{
SessionOpenOverrideForTests = _ => Task.CompletedTask,
@@ -303,6 +306,7 @@ public sealed class GalaxyDriverFixRound1Tests
await driver.SubscribeAsync(["Tank01.Level"], TimeSpan.Zero, CancellationToken.None);
driver.HasEventPumpForTests.ShouldBeTrue("positive control: subscribe works on a live runtime");
var oldPump = driver.EventPumpInstanceForTests;
sub.ParkUnsubscribe = true;
var shutdown = driver.ShutdownAsync(CancellationToken.None);
@@ -330,7 +334,12 @@ public sealed class GalaxyDriverFixRound1Tests
driver.TrackedSubscriptionCountForTests.ShouldBe(0);
await driver.InitializeAsync("{}", CancellationToken.None);
driver.HasEventPumpForTests.ShouldBeFalse("the next runtime starts with no inherited pump");
// #865: the new runtime's background probe seed starts a pump of its own (its advises need a live
// stream) — but it must be a FRESH one, never the dead subscriber's.
await WaitUntilAsync(() => driver.ProbeWatcherForTests?.WatchedPlatforms.Count == 1,
"positive control: the new runtime's background seed must advise its platform");
driver.EventPumpInstanceForTests.ShouldNotBeNull("the seed's probe advise must have started a pump")
.ShouldNotBeSameAs(oldPump, "the next runtime must not inherit the old pump");
}
// ───────────────────────────── IMPORTANT 3: bounded gateway close ─────────────────────────────
@@ -0,0 +1,419 @@
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Google.Protobuf.WellKnownTypes;
using Shouldly;
using Xunit;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// <summary>
/// #865: the platform ScanState probes' initial value. The gateway pushes an advise's current value
/// once, as its first event, and a FRESH <c>StreamEvents</c> (<c>after_worker_sequence = 0</c>) never
/// replays — so a probe advised before the driver's event stream is attached never gets a value, and
/// ScanState rarely changes again. The event pump used to start only on the first Read/Subscribe,
/// so a driver with no authored tags (or any driver before its first read) had no host statuses.
/// </summary>
public sealed class ProbeInitialValueTests
{
private static readonly string[] Platforms = ["CTRX_DEV", "DevWinPlatform", "DevAppEngine"];
private static GalaxyDriverOptions Opts() => new(
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
new GalaxyMxAccessOptions("ProbeInitialValue"),
new GalaxyRepositoryOptions(WatchDeployEvents: false),
new GalaxyReconnectOptions());
private sealed class FixedPlatformSource(params string[] platforms) : IGalaxyPlatformSource
{
public Task<IReadOnlyList<string>> GetPlatformTagNamesAsync(CancellationToken cancellationToken)
=> Task.FromResult<IReadOnlyList<string>>(platforms);
}
/// <summary>
/// Models the gateway's event semantics: every advise pushes its current value exactly once, and
/// only to a stream that is attached at that moment (no replay for a fresh stream). Records the
/// order in which the stream was requested and the advises were made.
/// </summary>
private sealed class GatewayLikeSubscriber : IGalaxySubscriber
{
private readonly Lock _gate = new();
private Channel<MxEvent>? _attached;
private int _nextHandle;
/// <summary>"stream" per StreamEvents call, "subscribe:&lt;refs&gt;" per SubscribeBulk, in call order.</summary>
public List<string> Calls { get; } = [];
/// <summary>Initial values pushed while no stream was attached — lost, as on the real gateway.</summary>
public int DroppedInitialValues;
private int _streams;
/// <summary>Streams beyond this count end immediately after attaching (a gateway refusing/ending them).</summary>
public int StreamsThatStayOpen = int.MaxValue;
/// <summary>The ScanState value the next advise reports.</summary>
public volatile bool ScanStateRunning = true;
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
{
var results = new List<SubscribeResult>();
lock (_gate)
{
Calls.Add("subscribe:" + string.Join(",", fullReferences));
foreach (var r in fullReferences)
{
var h = ++_nextHandle;
results.Add(new SubscribeResult { TagAddress = r, ItemHandle = h, WasSuccessful = true });
var initial = new MxEvent
{
Family = MxEventFamily.OnDataChange,
ItemHandle = h,
Value = new MxValue { BoolValue = ScanStateRunning },
Quality = 192,
SourceTimestamp = Timestamp.FromDateTime(DateTime.UtcNow),
};
if (_attached is null || !_attached.Writer.TryWrite(initial)) Interlocked.Increment(ref DroppedInitialValues);
}
}
return Task.FromResult<IReadOnlyList<SubscribeResult>>(results);
}
public Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken) => Task.CompletedTask;
public async IAsyncEnumerable<MxEvent> StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
// Attached synchronously on the first MoveNext — the point a real gRPC call is issued.
var mine = Channel.CreateUnbounded<MxEvent>();
lock (_gate)
{
Calls.Add("stream");
_attached = mine;
}
if (Interlocked.Increment(ref _streams) > StreamsThatStayOpen)
{
lock (_gate) { if (ReferenceEquals(_attached, mine)) _attached = null; }
yield break; // the gateway completed this stream at once
}
try
{
await foreach (var ev in mine.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
yield return ev;
}
}
finally
{
lock (_gate)
{
if (ReferenceEquals(_attached, mine)) _attached = null;
}
}
}
/// <summary>Fault the currently attached stream (the gateway dropping it).</summary>
public void FaultAttachedStream(Exception cause)
{
lock (_gate) _attached.ShouldNotBeNull("a stream must be attached").Writer.TryComplete(cause);
}
public string[] CallsSnapshot()
{
lock (_gate) return [.. Calls];
}
}
private static HostState? StateOf(GalaxyDriver driver, string host) =>
driver.GetHostStatuses().FirstOrDefault(s => s.HostName == host)?.State;
private static string Describe(GalaxyDriver driver, GatewayLikeSubscriber sub) =>
$"hosts=[{string.Join(", ", driver.GetHostStatuses().Select(s => $"{s.HostName}={s.State}"))}] " +
$"calls=[{string.Join(" | ", sub.CallsSnapshot())}] dropped={sub.DroppedInitialValues} pump={driver.HasEventPumpForTests}";
/// <summary>
/// A driver with NO authored tags — nothing ever Reads or Subscribes — still reports every seeded
/// platform with its initial ScanState. Before #865 the pump never started, every initial value
/// was pushed to no stream, and only the transport entry ever appeared.
/// </summary>
[Fact]
public async Task Driver_with_no_authored_tags_reports_every_platform_from_its_initial_ScanState()
{
var sub = new GatewayLikeSubscriber();
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub,
platformSource: new FixedPlatformSource(Platforms));
await driver.InitializeAsync("{}", CancellationToken.None);
await TestWait.UntilAsync(
() => Platforms.All(p => StateOf(driver, p) == HostState.Running),
"every seeded platform must surface Running from its initial ScanState, with no Read/Subscribe",
() => Describe(driver, sub));
sub.DroppedInitialValues.ShouldBe(0, "no probe's initial value may be pushed before the stream is attached");
driver.TrackedSubscriptionCountForTests.ShouldBe(1, "only the probe entry — no data subscription was ever made");
}
/// <summary>
/// Ordering: the event stream is requested BEFORE the first probe SubscribeBulk. On the old code
/// the probe advise went out with no stream at all.
/// </summary>
[Fact]
public async Task Probe_subscribe_is_issued_only_after_the_event_stream_is_requested()
{
var sub = new GatewayLikeSubscriber();
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub,
platformSource: new FixedPlatformSource(Platforms));
await driver.InitializeAsync("{}", CancellationToken.None);
await TestWait.UntilAsync(
() => driver.ProbeWatcherForTests?.WatchedPlatforms.Count == Platforms.Length,
"positive control: the background seed must advise every platform",
() => Describe(driver, sub));
var calls = sub.CallsSnapshot();
var firstSubscribe = Array.FindIndex(calls, c => c.StartsWith("subscribe:", StringComparison.Ordinal));
var firstStream = Array.IndexOf(calls, "stream");
firstSubscribe.ShouldBeGreaterThanOrEqualTo(0);
firstStream.ShouldBeGreaterThanOrEqualTo(0, $"the probe seed must start the event stream; calls=[{string.Join(" | ", calls)}]");
firstStream.ShouldBeLessThan(firstSubscribe, $"the stream must be requested before the probe advise; calls=[{string.Join(" | ", calls)}]");
}
/// <summary>
/// A reconnect replay re-advises the probes on the recreated session; their new initial values must
/// arrive too (the replay restarts the pump first). The value flips to Stopped so the presence wait
/// can only pass on a post-replay event.
/// </summary>
[Fact]
public async Task Reconnect_replay_delivers_the_re_advised_probes_initial_values()
{
var sub = new GatewayLikeSubscriber();
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub,
platformSource: new FixedPlatformSource(Platforms));
await driver.InitializeAsync("{}", CancellationToken.None);
await TestWait.UntilAsync(
() => Platforms.All(p => StateOf(driver, p) == HostState.Running),
"positive control: the initial seed reports Running",
() => Describe(driver, sub));
sub.ScanStateRunning = false;
await driver.InvokeReplayForTestAsync(CancellationToken.None);
await TestWait.UntilAsync(
() => Platforms.All(p => StateOf(driver, p) == HostState.Stopped),
"the re-advised probes' initial values (Stopped) must reach the host statuses after a replay",
() => Describe(driver, sub));
sub.DroppedInitialValues.ShouldBe(0);
}
/// <summary>
/// Review finding: a probe advised in the reopen → replay window (the session was swapped, the old
/// pump still streams the dead session) must still get its initial value. The advise waits for the
/// replay's restarted pump instead of advising onto the stale one (its value would route under the
/// old session and be lost, and the replay skips a current-session handle) or starting a competing
/// stream (the gateway's default single-subscriber mode refuses a second attach).
/// </summary>
[Fact]
public async Task Probe_advised_between_reopen_and_replay_still_gets_its_initial_value()
{
var sub = new GatewayLikeSubscriber();
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub,
platformSource: new FixedPlatformSource(Platforms))
{
RecreateOverrideForTests = _ => Task.CompletedTask,
// Generous: the window advise must still be waiting when the replay below starts the pump, even
// on a stalled agent; the wait ends the moment that pump exists.
StreamRequestWait = TimeSpan.FromSeconds(20),
};
await driver.InitializeAsync("{}", CancellationToken.None);
await TestWait.UntilAsync(
() => Platforms.All(p => StateOf(driver, p) == HostState.Running),
"positive control: the initial seed reports Running",
() => Describe(driver, sub));
var oldPump = driver.EventPumpInstanceForTests;
await driver.InvokeReopenForTestAsync(CancellationToken.None); // session swapped; no replay yet
sub.ScanStateRunning = false;
var callsBeforeWindow = sub.CallsSnapshot().Length;
// The window advise must WAIT for the replay's current-session pump rather than advise onto the
// stale one (or start a competing stream).
var sync = driver.ProbeWatcherForTests.ShouldNotBeNull()
.SyncPlatformsAsync([.. Platforms, "LatePlatform"], CancellationToken.None);
await driver.InvokeReplayForTestAsync(CancellationToken.None);
await TestWait.ForAsync(sync, "the window advise completes once the replay restarted the pump");
await TestWait.UntilAsync(
() => StateOf(driver, "LatePlatform") == HostState.Stopped
&& Platforms.All(p => StateOf(driver, p) == HostState.Stopped),
"the window advise and the replay's re-advises all get their initial values",
() => Describe(driver, sub));
driver.EventPumpInstanceForTests.ShouldNotBeSameAs(oldPump, "the replay restarted the stale pump");
var windowCalls = sub.CallsSnapshot()[callsBeforeWindow..];
var lateAdvise = Array.FindIndex(windowCalls, c => c.Contains("LatePlatform", StringComparison.Ordinal));
var newStream = Array.IndexOf(windowCalls, "stream");
newStream.ShouldBeGreaterThanOrEqualTo(0, $"the replay must start a new stream; calls=[{string.Join(" | ", windowCalls)}]");
lateAdvise.ShouldBeGreaterThan(newStream, $"the window advise must follow the new stream; calls=[{string.Join(" | ", windowCalls)}]");
windowCalls.Count(c => c == "stream").ShouldBe(1, "no competing stream may be started for the window advise");
sub.DroppedInitialValues.ShouldBe(0);
}
/// <summary>
/// The data paths too: a first SubscribeAsync and a first ReadAsync on a driver whose pump was never
/// started request the stream BEFORE advising, so their initial values arrive (a read of a value that
/// never changes again would otherwise time out).
/// </summary>
[Fact]
public async Task First_subscribe_and_read_advise_only_after_the_stream_is_requested()
{
var sub = new GatewayLikeSubscriber();
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub)
{
ReadViaSubscribeDeadline = TimeSpan.FromSeconds(10),
};
await driver.InitializeAsync("{}", CancellationToken.None);
var delivered = new TaskCompletionSource<DataChangeEventArgs>(TaskCreationOptions.RunContinuationsAsynchronously);
driver.OnDataChange += (_, e) => delivered.TrySetResult(e);
await driver.SubscribeAsync(["Tank01.Level"], TimeSpan.Zero, CancellationToken.None);
var calls = sub.CallsSnapshot();
Array.IndexOf(calls, "stream").ShouldBe(0, $"the stream must be requested before the advise; calls=[{string.Join(" | ", calls)}]");
(await TestWait.ForAsync(delivered.Task, "the subscribe's initial value must arrive", () => Describe(driver, sub)))
.FullReference.ShouldBe("Tank01.Level");
sub.DroppedInitialValues.ShouldBe(0);
}
/// <summary>A first ReadAsync on a fresh driver (no pump yet) requests the stream before its advise.</summary>
[Fact]
public async Task First_read_advises_only_after_the_stream_is_requested()
{
var sub = new GatewayLikeSubscriber();
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub)
{
ReadViaSubscribeDeadline = TimeSpan.FromSeconds(10),
};
await driver.InitializeAsync("{}", CancellationToken.None);
driver.HasEventPumpForTests.ShouldBeFalse("precondition: the read is the first advise");
var read = await driver.ReadAsync(["Tank02.Level"], CancellationToken.None);
var calls = sub.CallsSnapshot();
Array.IndexOf(calls, "stream").ShouldBe(0, $"the stream must be requested before the read's advise; calls=[{string.Join(" | ", calls)}]");
read[0].StatusCode.ShouldBe(0u, "the read's initial value must arrive (not BadTimeout)");
sub.DroppedInitialValues.ShouldBe(0);
}
/// <summary>
/// The replay's re-advise of DATA subscriptions (which has no per-advise hook) waits for the restarted
/// pump's stream, so each re-advised tag's new initial value arrives. The value flips so only a
/// post-replay event can satisfy the wait.
/// </summary>
[Fact]
public async Task Reconnect_replay_delivers_re_advised_data_subscriptions_initial_values()
{
var sub = new GatewayLikeSubscriber();
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub);
await driver.InitializeAsync("{}", CancellationToken.None);
var last = new System.Collections.Concurrent.ConcurrentDictionary<string, object?>();
driver.OnDataChange += (_, e) => last[e.FullReference] = e.Snapshot.Value;
await driver.SubscribeAsync(["Tank01.Level"], TimeSpan.Zero, CancellationToken.None);
await TestWait.UntilAsync(() => last.TryGetValue("Tank01.Level", out var v) && v is true,
"positive control: the subscribe's initial value arrives", () => Describe(driver, sub));
sub.ScanStateRunning = false; // the fake's next initial value
await driver.InvokeReplayForTestAsync(CancellationToken.None);
await TestWait.UntilAsync(() => last.TryGetValue("Tank01.Level", out var v) && v is false,
"the replay's re-advise must deliver its new initial value",
() => Describe(driver, sub) + $" last=[{string.Join(",", last.Select(kv => $"{kv.Key}={kv.Value}"))}] parked={driver.ParkedEarlyEventCountForTests} h2=[{string.Join(",", driver.SubscriptionsForTests.ResolveSubscribers(2).Select(b => b.FullReference))}] h1=[{string.Join(",", driver.SubscriptionsForTests.ResolveSubscribers(1).Select(b => b.FullReference))}]");
sub.DroppedInitialValues.ShouldBe(0);
}
/// <summary>
/// A replay whose restarted pump's stream ends at once must FAIL (the supervisor then backs off and
/// stays Degraded) rather than succeed onto a dead stream — succeeding went Healthy, and the next
/// advise's re-report started a new cycle with no backoff: a tight reconnect loop. Positive control:
/// the first replay, whose stream stays open, succeeds.
/// </summary>
[Fact]
public async Task Replay_fails_when_the_restarted_stream_ends_at_once()
{
var sub = new GatewayLikeSubscriber { StreamsThatStayOpen = 2 };
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub);
await driver.InitializeAsync("{}", CancellationToken.None);
await driver.SubscribeAsync(["Tank01.Level"], TimeSpan.Zero, CancellationToken.None); // stream 1
await driver.InvokeReplayForTestAsync(CancellationToken.None); // stream 2 stays open — succeeds
await Should.ThrowAsync<InvalidOperationException>(
() => driver.InvokeReplayForTestAsync(CancellationToken.None), // stream 3 ends at once
"a replay must not report success over a dead event stream");
}
/// <summary>
/// #865 review: a stream fault is escalated only from the LIVE pump. A fault from a pump superseded
/// by a reopen (its session is no longer current) is ignored — it would fail a good replay — while
/// the live pump's faults (before the reopen, and the replay's new pump after it) still escalate.
/// </summary>
[Fact]
public async Task Only_the_live_pumps_stream_faults_are_escalated()
{
var sub = new GatewayLikeSubscriber();
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub)
{
RecreateOverrideForTests = _ => Task.CompletedTask,
};
await driver.InitializeAsync("{}", CancellationToken.None);
await driver.SubscribeAsync(["Tank01.Level"], TimeSpan.Zero, CancellationToken.None); // pump 1
// Positive control: the live pump's fault escalates.
sub.FaultAttachedStream(new IOException("drop 1"));
await TestWait.UntilAsync(() => driver.EscalatedStreamFaultsForTests == 1, "the live pump's fault must escalate");
// Recover onto pump 2 (the replay restarts the faulted pump), then reopen: pump 2 is now superseded.
await driver.InvokeReplayForTestAsync(CancellationToken.None);
var pump2 = driver.EventPumpInstanceForTests.ShouldNotBeNull();
await driver.InvokeReopenForTestAsync(CancellationToken.None);
sub.FaultAttachedStream(new IOException("late fault from the superseded pump"));
await TestWait.UntilAsync(() => ((EventPump)pump2).HasEnded, "the superseded pump's stream must have faulted");
// Positive control after the absence: the replay's new pump faults and that DOES escalate — so the
// count can only be 2 if the superseded pump's fault was ignored.
await driver.InvokeReplayForTestAsync(CancellationToken.None);
var pump3 = (EventPump)driver.EventPumpInstanceForTests.ShouldNotBeNull();
pump3.ShouldNotBeSameAs(pump2);
sub.FaultAttachedStream(new IOException("drop 3"));
// HasEnded is set only after the fault callback ran, so once both pumps have ended every escalation
// that will ever happen has happened.
await TestWait.UntilAsync(() => pump3.HasEnded, "the new live pump's stream must have faulted");
driver.EscalatedStreamFaultsForTests.ShouldBe(2, "the new live pump's fault escalates; the superseded pump's did not");
}
/// <summary>
/// A probe sync on a driver whose pump was never started (no platform source, e.g. the
/// DiscoverAsync path) still starts it before advising — the watcher's pre-subscribe hook, not just
/// the init path.
/// </summary>
[Fact]
public async Task Probe_sync_without_a_platform_source_still_starts_the_stream_first()
{
var sub = new GatewayLikeSubscriber();
// No platform source: init starts no pump; the probe set arrives through SyncPlatformsAsync.
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub);
await driver.InitializeAsync("{}", CancellationToken.None);
driver.HasEventPumpForTests.ShouldBeFalse("precondition: nothing has started the pump yet");
await driver.ProbeWatcherForTests.ShouldNotBeNull().SyncPlatformsAsync(Platforms, CancellationToken.None);
await TestWait.UntilAsync(
() => Platforms.All(p => StateOf(driver, p) == HostState.Running),
"the watcher must start the stream before advising, so the initial values arrive",
() => Describe(driver, sub));
sub.DroppedInitialValues.ShouldBe(0);
}
}
@@ -15,6 +15,85 @@ public sealed class ReconnectSupervisorTests
new(InitialBackoffOverride: TimeSpan.FromMilliseconds(5),
MaxBackoffOverride: TimeSpan.FromMilliseconds(20));
/// <summary>
/// #865: AttemptInProgress is true while a reopen (through the replay) runs and FALSE during the backoff
/// between attempts — when the state still reads Reopening. Advises wait for a replay only while one is
/// actually running, not for a whole backoff.
/// </summary>
[Fact]
public async Task AttemptInProgress_is_true_during_an_attempt_and_false_during_the_backoff()
{
var reopenEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseReopen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var reopens = 0;
using var sup = new ReconnectSupervisor(
reopen: async _ =>
{
if (Interlocked.Increment(ref reopens) == 1)
{
reopenEntered.TrySetResult();
await releaseReopen.Task;
throw new IOException("gateway still down");
}
},
replay: _ => Task.CompletedTask,
backoffDelay: (_, _, _) => TimeSpan.FromMinutes(10)); // park in the backoff
sup.AttemptInProgress.ShouldBeFalse("Healthy: no attempt");
sup.ReportTransportFailure(new IOException("drop"));
await TestWait.ForAsync(reopenEntered.Task, "the first reopen must start");
sup.AttemptInProgress.ShouldBeTrue("a reopen is running");
releaseReopen.SetResult(); // the reopen fails -> backoff of 10 min
await TestWait.UntilAsync(() => !sup.AttemptInProgress, "the failed attempt must clear the flag");
sup.CurrentState.ShouldBe(ReconnectSupervisor.State.Reopening, "the backoff still reads Reopening — why the flag exists");
}
/// <summary>
/// #865 review: a transport failure reported WHILE the replay runs (e.g. the restarted event stream is
/// refused a round trip later) must fail that attempt — not go Healthy over a dead transport. The
/// supervisor retries (with backoff) and goes Healthy only after a clean replay. Without the fix the
/// first replay's success went Healthy and replay ran once.
/// </summary>
[Fact]
public async Task A_failure_reported_during_the_replay_fails_that_attempt()
{
ReconnectSupervisor? self = null;
var replays = 0;
using var sup = new ReconnectSupervisor(
reopen: _ => Task.CompletedTask,
replay: _ =>
{
if (Interlocked.Increment(ref replays) == 1)
{
self!.ReportTransportFailure(new IOException("stream refused during replay"));
}
return Task.CompletedTask;
},
options: FastBackoff());
self = sup;
sup.ReportTransportFailure(new IOException("drop"));
await TestWait.HealthyAsync(sup, "the second, clean replay must recover");
Volatile.Read(ref replays).ShouldBe(2, "the faulted replay must not count as recovered");
}
/// <summary>#865: a transport failure reported after StopAsync never starts a recovery loop (it throws ODE).</summary>
[Fact]
public async Task ReportTransportFailure_after_stop_never_starts_a_loop()
{
var reopens = 0;
var sup = new ReconnectSupervisor(
reopen: _ => { Interlocked.Increment(ref reopens); return Task.CompletedTask; },
replay: _ => Task.CompletedTask,
options: FastBackoff());
await sup.StopAsync();
Should.Throw<ObjectDisposedException>(() => sup.ReportTransportFailure(new IOException("late")));
sup.CurrentState.ShouldBe(ReconnectSupervisor.State.Healthy);
Volatile.Read(ref reopens).ShouldBe(0);
}
/// <summary>Verifies that the supervisor starts in a healthy state with no errors.</summary>
[Fact]
public void InitialState_IsHealthy()
@@ -0,0 +1,133 @@
using System.Buffers.Binary;
using System.Text;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests.Simulator;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests;
/// <summary>
/// lmxopcua#867: the published value's RUNTIME type must be the CLR type of the leaf's declared data type.
/// Shouldly equality cannot catch this (7.0 equals 7L), so every assertion here compares <c>GetType()</c>.
/// </summary>
[Trait("Category", "Unit")]
public sealed class HeidenhainLeafRuntimeTypeTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static Type ClrType(DriverDataType type, bool isArray)
{
var scalar = type switch
{
DriverDataType.Boolean => typeof(bool),
DriverDataType.Int16 => typeof(short),
DriverDataType.Int32 => typeof(int),
DriverDataType.Int64 => typeof(long),
DriverDataType.Float64 => typeof(double),
DriverDataType.String => typeof(string),
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
return isArray ? scalar.MakeArrayType() : scalar;
}
/// <summary>Every fixed value leaf (capability strings excluded), with its declared type.</summary>
public static TheoryData<string> CatalogValueLeaves()
{
var data = new TheoryData<string>();
foreach (var e in HeidenhainCatalog.Entries.Where(e => !e.IsCapability)) data.Add(e.Address);
return data;
}
private static SimulatedControl FullyPopulatedControl()
{
var c = new SimulatedControl();
c.Runtime[22] = () => SimReply.Ok("S_RI", [0, 1, .. Encoding.ASCII.GetBytes("1.5\0X\0")]);
c.Runtime[23] = () => SimReply.Ok("S_RI", [0, 4]);
c.Runtime[26] = () => SimReply.Ok("S_RI", [0, 7]);
c.Runtime[24] = () => SimReply.Ok("S_RI", [0, 0, 0, 5, .. "A\0B\0"u8.ToArray()]);
c.Runtime[25] = () => SimReply.Ok("S_RI", new byte[12]);
var alarm = new byte[10];
BinaryPrimitives.WriteInt16BigEndian(alarm, 3);
BinaryPrimitives.WriteInt16BigEndian(alarm.AsSpan(2), 4);
BinaryPrimitives.WriteInt32BigEndian(alarm.AsSpan(4), 12);
alarm[8] = 65;
c.Runtime[27] = () => SimReply.Ok("S_RI", alarm);
c.Runtime[28] = () => SimReply.Refuse(57);
// 24-byte tool reply: number 49, index 1, axis 2, length 100.5, radius 3.25 (float64le).
var tool = new byte[24];
BinaryPrimitives.WriteUInt32BigEndian(tool, 49);
BinaryPrimitives.WriteUInt16BigEndian(tool.AsSpan(4), 1);
BinaryPrimitives.WriteUInt16BigEndian(tool.AsSpan(6), 2);
BinaryPrimitives.WriteDoubleLittleEndian(tool.AsSpan(8), 100.5);
BinaryPrimitives.WriteDoubleLittleEndian(tool.AsSpan(16), 3.25);
c.Runtime[51] = () => SimReply.Ok("S_RI", tool);
for (var s = 30; s <= 34; s++) c.Runtime[s] = () => SimReply.Ok("S_RI", [0, 0, 1, 0]);
return c;
}
[Theory]
[MemberData(nameof(CatalogValueLeaves))]
public async Task Catalog_leaf_publishes_the_clr_type_of_its_declared_data_type(string address)
{
HeidenhainCatalog.TryGet(address, out var entry).ShouldBeTrue();
var control = FullyPopulatedControl();
await using var sim = Lsv2Simulator.WithControl(control);
var client = new Lsv2.Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromSeconds(1));
var tag = TestTags.Def(address);
var settings = new HeidenhainSessionSettings(true, true, false, 64, true, false, false);
await using var session = new HeidenhainSession(client, settings, (_, _) => ValueTask.FromResult(""));
await client.OpenAsync(Ct);
await session.InitializeAsync(Ct);
var sample = (await session.ReadBatchAsync([tag], Ct))[0];
sample.Status.ShouldBe(HeidenhainStatus.Good, address);
sample.Value.ShouldNotBeNull(address);
sample.Value.GetType().ShouldBe(ClrType(entry!.DataType, entry.IsArray), address);
control.Violations.ShouldBeEmpty();
}
[Fact]
public void Every_integer_catalog_leaf_is_covered()
{
// Pins the theory's reach: the integer leaves #867 broke are in the data set.
var leaves = CatalogValueLeaves().Select(r => r.Data).ToList();
leaves.ShouldContain("Tool/Number");
leaves.ShouldContain("Tool/Index");
leaves.ShouldContain("Tool/AxisCode");
leaves.ShouldContain("Alarms/Count");
leaves.ShouldContain("Program/Line");
leaves.ShouldContain("Status/ExecutionState");
leaves.Count(l => l.StartsWith("Timers/", StringComparison.Ordinal)).ShouldBe(HeidenhainCatalog.TimerNames.Count);
}
[Theory]
[InlineData(DriverDataType.Int16, 42)]
[InlineData(DriverDataType.Int32, 42)]
[InlineData(DriverDataType.Int64, 42)]
[InlineData(DriverDataType.Int16, 42L)]
[InlineData(DriverDataType.Int32, 42L)]
[InlineData(DriverDataType.Int64, 42L)]
[InlineData(DriverDataType.Int16, 42.0)]
[InlineData(DriverDataType.Int32, 42.0)]
[InlineData(DriverDataType.Int64, 42.0)]
[InlineData(DriverDataType.Boolean, true)]
[InlineData(DriverDataType.Boolean, false)]
public void Binding_coercion_publishes_the_clr_type_of_the_declared_data_type(DriverDataType type, object native)
{
HeidenhainBindingCodec.Coerce(native, type).GetType().ShouldBe(ClrType(type, false));
}
[Theory]
[InlineData(HeidenhainPlcArea.Byte, new byte[] { 7 }, DriverDataType.Int16)]
[InlineData(HeidenhainPlcArea.Byte, new byte[] { 7 }, DriverDataType.Int32)]
[InlineData(HeidenhainPlcArea.Word, new byte[] { 7, 0 }, DriverDataType.Int64)]
[InlineData(HeidenhainPlcArea.Dword, new byte[] { 7, 0, 0, 0 }, DriverDataType.Int32)]
[InlineData(HeidenhainPlcArea.InputWord, new byte[] { 7, 0 }, DriverDataType.Int32)]
[InlineData(HeidenhainPlcArea.Marker, new byte[] { 1 }, DriverDataType.Boolean)]
public void Plc_binding_decode_publishes_the_clr_type_of_the_declared_data_type(HeidenhainPlcArea area, byte[] bytes, DriverDataType type)
{
HeidenhainBindingCodec.DecodePlc(area, bytes, type).GetType().ShouldBe(ClrType(type, false));
}
}
@@ -414,9 +414,10 @@ public sealed class SdkAggregateParityTests
public void PercentGood_keeps_Uncertain_out_of_Good_per_Part_13_where_the_baseline_SDK_counts_it_as_Good(
double from, double to)
{
// #796, documented divergence (SdkAggregateOracle remarks). Part 13 §5.4.3.31 / §5.4.3.33: PercentGood is the Good
// share of the interval. The 1.5.378.182 StatusAggregateCalculator, under the server's TreatUncertainAsBad = false,
// adds Uncertain regions to it (1.5.378.106 did not). Hand-computed over 4 × 5 s regions G / U / B / G:
// #796, documented divergence of the untouched baseline (SdkAggregateOracle remarks; live follows Part 13 since
// #809). Part 13 §5.4.3.31 / §5.4.3.33: PercentGood is the Good share of the interval. The 1.5.378.182
// StatusAggregateCalculator, under the server's TreatUncertainAsBad = false, adds Uncertain regions to it
// (1.5.378.106 did not). Hand-computed over 4 × 5 s regions G / U / B / G:
// Good 10 s ⇒ 50 %, Bad 5 s ⇒ 25 %, Uncertain 5 s in neither; the baseline says 75 % Good.
Pct(AsIs(HistoryAggregateType.PercentGood, from, to, GoodUncertainBadGood))
.ShouldBe(75d, 1e-9, "the baseline counts the Uncertain 5 s as Good — if this moves, revisit the oracle (#796)");
@@ -524,16 +525,19 @@ public sealed class SdkAggregateParityTests
public void An_Uncertain_first_sample_in_a_late_start_interval_makes_the_SDK_integrate_the_time_before_the_data(
double from, double to)
{
// #821, pinned divergence (pending the #809/#821 owner decision — this test records, it does not choose).
// Part 13 §5.4.3.3/§5.4.3.8: the interpolated-bounding signal is defined from the first sample only — 10 → 11 over
// [5,12) (73.5) and 11 → 11 + 8/13 over [12,20) (4·(22 + 8/13)) ⇒ Total 163.96…, TimeAverage = Total ÷ 15 s.
// #821, decided 2026-11-11: live follows Part 13. Part 13 §5.4.3.6/§5.4.3.8 ("No Start Bound: Calculate Partial
// Interval"): the interpolated-bounding signal is defined from the first sample only — 10 → 11 over [5,12) (73.5)
// and 11 → 11 + 8/13 over [12,20) (4·(22 + 8/13)) ⇒ Total 163.96…, TimeAverage = Total ÷ 15 s.
const double part13Total = 73.5 + 88 + 32d / 13;
Pct(Ours(HistoryAggregateType.Total, from, to, 0, UncertainFirstLateStart)).ShouldBe(part13Total, 1e-9);
Pct(Ours(HistoryAggregateType.TimeAverage, from, to, 0, UncertainFirstLateStart)).ShouldBe(part13Total / 15, 1e-9);
// The live AggregateFilter calculators (CompatibilityAggregateFactory — CoveredTimeAverageAggregateCalculator since
// #821; Sdk2AggregateCompatibilityTests proves the runtime manager serves the same code) answer the same.
Pct(Sdk(HistoryAggregateType.Total, from, to, 0, UncertainFirstLateStart)).ShouldBe(part13Total, 1e-9);
Pct(Sdk(HistoryAggregateType.TimeAverage, from, to, 0, UncertainFirstLateStart)).ShouldBe(part13Total / 15, 1e-9);
// The frozen 1.5.378.182 calculators — exactly what the server registers for live AggregateFilter items
// (CompatibilityAggregateFactory; Sdk2AggregateCompatibilityTests proves the runtime manager serves the same code)
// — integrate the uncovered [0,5) as a ramp 0 → 10 (+25) and divide TimeAverage by the WHOLE 20 s interval.
// The untouched frozen 1.5.378.182 calculators (live before #821) integrate the uncovered [0,5) as a ramp 0 → 10
// (+25) and divide TimeAverage by the WHOLE 20 s interval.
Pct(AsIs(HistoryAggregateType.Total, from, to, UncertainFirstLateStart)).ShouldBe(part13Total + 25, 1e-9);
Pct(AsIs(HistoryAggregateType.TimeAverage, from, to, UncertainFirstLateStart)).ShouldBe((part13Total + 25) / 20, 1e-9);
// SDK 2.0.1's own stock calculators answer the same: the upgrade did not change this.
@@ -544,29 +548,183 @@ public sealed class SdkAggregateParityTests
// Status agrees everywhere (Uncertain — an Uncertain value is used and the interval is not fully covered).
(AsIs(HistoryAggregateType.Total, from, to, UncertainFirstLateStart).Single().StatusCode & StatusBits.CodeBitsMask)
.ShouldBe(HistorianStatusCodes.UncertainDataSubNormal);
Sdk(HistoryAggregateType.Total, from, to, 0, UncertainFirstLateStart).Single().StatusCode
.ShouldBe(AsIs(HistoryAggregateType.Total, from, to, UncertainFirstLateStart).Single().StatusCode);
(Ours(HistoryAggregateType.Total, from, to, 0, UncertainFirstLateStart).Single().StatusCode & StatusBits.CodeBitsMask)
.ShouldBe(HistorianStatusCodes.UncertainDataSubNormal);
// Control: the SAME data with a Good first sample — all three agree on the Part 13 answer, so the trigger is the
// Control: the SAME data with a Good first sample — all agree on the Part 13 answer, so the trigger is the
// Uncertain first sample, not the late start.
foreach (var agg in new[] { HistoryAggregateType.Total, HistoryAggregateType.TimeAverage })
{
var expected = agg == HistoryAggregateType.Total ? part13Total : part13Total / 15;
Pct(Ours(agg, from, to, 0, GoodFirstLateStart)).ShouldBe(expected, 1e-9);
Pct(Sdk(agg, from, to, 0, GoodFirstLateStart)).ShouldBe(expected, 1e-9);
Pct(AsIs(agg, from, to, GoodFirstLateStart)).ShouldBe(expected, 1e-9);
Stock201(agg, from, to, GoodFirstLateStart).Single().Value!.Value.ShouldBe(expected, 1e-9);
}
// #809 on the same input: DurationGood / PercentGood — Part 13 (ours) and stock SDK 2.0.1 count Good regions only
// ([12,20) = 8 s); the frozen live calculators also count the Uncertain [5,12) as Good (15 s).
// #809 on the same input: DurationGood / PercentGood — Part 13 (ours), stock SDK 2.0.1 and, since #809, the live
// calculators count Good regions only ([12,20) = 8 s); the untouched baseline (live before #809) also counted the
// Uncertain [5,12) as Good (15 s).
Pct(Ours(HistoryAggregateType.DurationGood, from, to, 0, UncertainFirstLateStart)).ShouldBe(8_000d, 1e-9);
Stock201(HistoryAggregateType.DurationGood, from, to, UncertainFirstLateStart).Single().Value!.Value.ShouldBe(8_000d, 1e-9);
Pct(Sdk(HistoryAggregateType.DurationGood, from, to, 0, UncertainFirstLateStart)).ShouldBe(8_000d, 1e-9);
Pct(AsIs(HistoryAggregateType.DurationGood, from, to, UncertainFirstLateStart)).ShouldBe(15_000d, 1e-9);
Pct(Ours(HistoryAggregateType.PercentGood, from, to, 0, UncertainFirstLateStart)).ShouldBe(40d, 1e-9);
Stock201(HistoryAggregateType.PercentGood, from, to, UncertainFirstLateStart).Single().Value!.Value.ShouldBe(40d, 1e-9);
Pct(Sdk(HistoryAggregateType.PercentGood, from, to, 0, UncertainFirstLateStart)).ShouldBe(40d, 1e-9);
Pct(AsIs(HistoryAggregateType.PercentGood, from, to, UncertainFirstLateStart)).ShouldBe(75d, 1e-9);
}
/// <summary>
/// #809: the #810 QualityMix tag Q — Good / Uncertain / Bad samples and an outage marker, Uncertain regions starting
/// at a sample, through a sloped bound and held into an outage, with Good samples before (−10) and after (+90) every
/// window so no interval holds the start or the end of the data.
/// </summary>
private static readonly StoredSample[] UncertainMix =
[
S(-10, HistorianValue.FromDouble(10), Good),
S(0, HistorianValue.FromDouble(10), Good),
S(4, HistorianValue.FromDouble(12), Uncertain),
S(7, HistorianValue.FromDouble(13), Bad),
S(10, HistorianValue.FromDouble(14), Good),
S(13, HistorianValue.FromDouble(15), Uncertain),
S(20, HistorianValue.FromDouble(16), Uncertain),
S(25, HistorianValue.FromDouble(17), Uncertain),
S(33, HistorianValue.FromDouble(18), Uncertain),
S(40, HistorianValue.FromDouble(20), Good),
S(45, HistorianValue.Empty, BadNoCommunication),
S(50, HistorianValue.FromDouble(22), Uncertain),
S(56, HistorianValue.FromDouble(23), Good),
S(64, HistorianValue.FromDouble(25), Uncertain),
S(67, HistorianValue.FromDouble(26), Good),
S(75, HistorianValue.FromDouble(27), Bad),
S(78, HistorianValue.FromDouble(28), Good),
S(90, HistorianValue.FromDouble(30), Good),
];
/// <summary>Windows of whole intervals only (no truncated interval — ours flags it Partial, a documented divergence).</summary>
public static TheoryData<double, double, double> WholeIntervalWindows => new()
{
{ 0, 80, 20 }, { 80, 0, 20 },
{ 0, 80, 10 }, { 80, 0, 10 },
{ 5, 80, 15 }, { 80, 5, 15 },
{ 0, 60, 0 }, { 60, 0, 0 },
};
[Theory]
[MemberData(nameof(WholeIntervalWindows))]
public void Live_AggregateFilter_PercentGood_and_DurationGood_equal_HistoryRead_over_Uncertain_samples(
double from, double to, double intervalS)
{
// #809: a live AggregateFilter monitored item and a HistoryRead-Processed (SqlServer / QuestDB share
// TimeWeightedAggregator) answer PercentGood / DurationGood identically over Uncertain data — same values,
// timestamps, status and Partial / Calculated bits, with NO documented-divergence mask. RunLive is exactly
// CompatibilityAggregateFactory.Create, the calculator the server registers (Sdk2AggregateCompatibilityTests
// proves the booted runtime manager serves the same code).
var interval = intervalS > 0 ? TimeSpan.FromSeconds(intervalS) : (At(to) - At(from)).Duration();
var failures = new List<string>();
var discriminated = 0;
foreach (var agg in new[] { HistoryAggregateType.PercentGood, HistoryAggregateType.DurationGood })
foreach (var (name, data) in new[] { ("UncertainMix", UncertainMix), ("DenseUncertain", DenseUncertain) })
{
var rows = data.Select(x => (x.TimeUtc, x.Value, x.Status)).ToArray();
var live = SdkAggregateOracle.RunLive(agg, At(from), At(to), interval, rows);
try
{
SdkAggregateOracle.ShouldMatch(Ours(agg, from, to, intervalS, data), live, $"live {agg} {name} {from}→{to}/{intervalS}s");
}
catch (Exception ex)
{
failures.Add(ex.Message);
}
// The data must discriminate: the pre-#809 live calculator (the untouched baseline) counts the Uncertain
// time as Good, so it disagrees somewhere — or this parity would pass against the old behaviour too.
var before = SdkAggregateOracle.RunSdkAsIs(agg, At(from), At(to), interval, rows);
if (before.Zip(live).Any(p => Math.Abs(Convert.ToDouble(p.First.Value) - Convert.ToDouble(p.Second.Value)) > 1e-9))
discriminated++;
}
failures.ShouldBeEmpty(string.Join("\n", failures));
discriminated.ShouldBe(4, "every aggregate × data set must differ from the pre-#809 live answer somewhere");
}
[Fact]
public void Live_AggregateFilter_PercentGood_and_DurationGood_are_the_hand_computed_Part_13_values()
{
// #809, hand-computed over UncertainMix's eight 10 s intervals (QualityMixConformance derives them region by
// region): Good seconds 4, 3, 0, 0, 5, 4, 3, 2. The pre-#809 live answer added the Uncertain time
// (7, 10, 10, 10, 5, 10, 10, 7 s).
double[] goodSeconds = [4, 3, 0, 0, 5, 4, 3, 2];
var rows = UncertainMix.Select(x => (x.TimeUtc, x.Value, x.Status)).ToArray();
var ten = TimeSpan.FromSeconds(10);
SdkAggregateOracle.RunLive(HistoryAggregateType.DurationGood, At(0), At(80), ten, rows)
.Select(r => Convert.ToDouble(r.Value)).ShouldBe(goodSeconds.Select(g => g * 1000), tolerance: 1e-9);
SdkAggregateOracle.RunLive(HistoryAggregateType.PercentGood, At(0), At(80), ten, rows)
.Select(r => Convert.ToDouble(r.Value)).ShouldBe(goodSeconds.Select(g => g * 10), tolerance: 1e-9);
SdkAggregateOracle.RunSdkAsIs(HistoryAggregateType.DurationGood, At(0), At(80), ten, rows)
.Select(r => Convert.ToDouble(r.Value)).ShouldBe([7000d, 10000, 10000, 10000, 5000, 10000, 10000, 7000], tolerance: 1e-9);
}
/// <summary>
/// #821: late-start data whose first usable sample is Uncertain (+7, after every window's start), with Good / Uncertain / Bad samples after it
/// and a Good sample past every window's end (+90), so only the start of the data is in question. No sample sits on
/// an interval edge of <see cref="WholeIntervalWindows"/> (the reverse on-edge divergence, class remarks).
/// </summary>
private static readonly StoredSample[] UncertainFirstLate =
[
S(7, HistorianValue.FromDouble(10), Uncertain),
S(12, HistorianValue.FromDouble(11), Good),
S(25, HistorianValue.FromDouble(12), Uncertain),
S(33, HistorianValue.FromDouble(14), Good),
S(47, HistorianValue.FromDouble(13), Bad),
S(52, HistorianValue.FromDouble(15), Good),
S(90, HistorianValue.FromDouble(16), Good),
];
/// <summary>#821: the same, preceded by Bad samples only (an outage before the data — still no start bound).</summary>
private static readonly StoredSample[] BadThenUncertainFirstLate =
[
S(-10, HistorianValue.Empty, BadNoCommunication),
S(2, HistorianValue.FromDouble(7), Bad),
.. UncertainFirstLate,
];
[Theory]
[MemberData(nameof(WholeIntervalWindows))]
public void Live_AggregateFilter_TimeAverage_and_Total_equal_HistoryRead_over_an_Uncertain_first_late_start(
double from, double to, double intervalS)
{
// #821: a live AggregateFilter monitored item and a HistoryRead-Processed (SqlServer / QuestDB share
// TimeWeightedAggregator) answer TimeAverage / Total identically when the data starts inside an interval with an
// Uncertain value — same values, timestamps, status and Partial / Calculated bits, NO documented-divergence mask.
// RunLive is exactly CompatibilityAggregateFactory.Create, the calculator the server registers.
var interval = intervalS > 0 ? TimeSpan.FromSeconds(intervalS) : (At(to) - At(from)).Duration();
var failures = new List<string>();
var discriminated = 0;
foreach (var agg in new[] { HistoryAggregateType.TimeAverage, HistoryAggregateType.Total })
foreach (var (name, data) in new[] { ("UncertainFirstLate", UncertainFirstLate), ("BadThenUncertainFirstLate", BadThenUncertainFirstLate) })
{
var rows = data.Select(x => (x.TimeUtc, x.Value, x.Status)).ToArray();
var live = SdkAggregateOracle.RunLive(agg, At(from), At(to), interval, rows);
try
{
SdkAggregateOracle.ShouldMatch(Ours(agg, from, to, intervalS, data), live, $"live {agg} {name} {from}→{to}/{intervalS}s");
}
catch (Exception ex)
{
failures.Add(ex.Message);
}
// The data must discriminate: the pre-#821 live calculator (the untouched baseline) integrates the span before
// the data, so it disagrees on the late-start interval — or this parity would pass against the old behaviour too.
var before = SdkAggregateOracle.RunSdkAsIs(agg, At(from), At(to), interval, rows);
if (before.Zip(live).Any(p => Math.Abs(Convert.ToDouble(p.First.Value) - Convert.ToDouble(p.Second.Value)) > 1e-9))
discriminated++;
}
failures.ShouldBeEmpty(string.Join("\n", failures));
discriminated.ShouldBe(4, "every aggregate × data set must differ from the pre-#821 live answer somewhere");
}
/// <summary>#684: Good 10 / 30 with an Uncertain value BELOW the Good minimum (+4) and one ABOVE the maximum (+6).</summary>
private static readonly StoredSample[] UncertainBeyond =
[
@@ -320,21 +320,107 @@ public sealed class MTConnectObservationIndexTests
.ShouldBe(new DateTime(2026, 7, 24, 12, 0, 0, 500, DateTimeKind.Utc));
}
/// <summary>An observation whose text is empty is "the Agent supplied no value" — never a Good empty string.</summary>
/// <summary>
/// lmxopcua#824 (Java parity): an empty element on a string-typed item is a Good empty string, not an
/// absence. Whitespace-only text is the same (the parser trims it).
/// </summary>
[Theory]
[InlineData("")]
[InlineData(" ")]
public void Empty_observation_value_maps_to_BadNoCommunication(string value)
[InlineData("", DriverDataType.String)]
[InlineData(" ", DriverDataType.String)]
[InlineData("", DriverDataType.Reference)]
public void Empty_observation_value_on_a_string_item_is_a_Good_empty_string(string value, DriverDataType type)
{
var idx = new MTConnectObservationIndex([Tag("x", DriverDataType.String)]);
var idx = new MTConnectObservationIndex([Tag("x", type)]);
idx.Apply(Synthetic("x", value));
var snap = idx.Get("x");
snap.StatusCode.ShouldBe(Good);
snap.Value.ShouldBe(string.Empty);
}
/// <summary>An unauthored item coerces as String, so its empty value is a Good empty string too (#824).</summary>
[Fact]
public void Empty_observation_value_on_an_unauthored_item_is_a_Good_empty_string()
{
var idx = new MTConnectObservationIndex();
idx.Apply(Synthetic("x", ""));
var snap = idx.Get("x");
snap.StatusCode.ShouldBe(Good);
snap.Value.ShouldBe(string.Empty);
}
/// <summary>
/// #824: on a non-string item "" cannot be a value, so it stays BadNoCommunication (the Agent supplied
/// no value) — not BadTypeMismatch, which would blame the tag's authored type.
/// </summary>
[Theory]
[InlineData(DriverDataType.Float64)]
[InlineData(DriverDataType.Float32)]
[InlineData(DriverDataType.Int32)]
[InlineData(DriverDataType.Int64)]
[InlineData(DriverDataType.Boolean)]
[InlineData(DriverDataType.DateTime)]
public void Empty_observation_value_on_a_non_string_item_stays_BadNoCommunication(DriverDataType type)
{
var idx = new MTConnectObservationIndex([Tag("x", type)]);
idx.Apply(Synthetic("x", " "));
var snap = idx.Get("x");
snap.StatusCode.ShouldBe(BadNoCommunication);
snap.Value.ShouldBeNull();
}
/// <summary>
/// #824 control: the UNAVAILABLE sentinel is unaffected — still BadNoCommunication on a String item, where an
/// empty value is now Good.
/// </summary>
[Fact]
public void Unavailable_on_a_string_item_is_still_BadNoCommunication()
{
var idx = new MTConnectObservationIndex([Tag("x", DriverDataType.String)]);
idx.Apply(Synthetic("x", "UNAVAILABLE"));
var snap = idx.Get("x");
snap.StatusCode.ShouldBe(BadNoCommunication);
snap.Value.ShouldBeNull();
}
/// <summary>#824 end to end through the parser: an empty, a self-closing and a blank element are all Good "".</summary>
[Theory]
[InlineData("""<Program dataItemId="p" timestamp="2026-07-24T12:00:00Z" sequence="1"></Program>""")]
[InlineData("""<Program dataItemId="p" timestamp="2026-07-24T12:00:00Z" sequence="1"/>""")]
[InlineData("""<Program dataItemId="p" timestamp="2026-07-24T12:00:00Z" sequence="1"> </Program>""")]
public void A_parsed_empty_event_on_a_string_item_is_a_Good_empty_string(string element)
{
var idx = new MTConnectObservationIndex([Tag("p", DriverDataType.String)]);
idx.Apply(MTConnectStreamsParser.Parse($"""
<MTConnectStreams>
<Header instanceId="1" nextSequence="2" firstSequence="1"/>
<Streams><DeviceStream><ComponentStream><Events>{element}</Events></ComponentStream></DeviceStream></Streams>
</MTConnectStreams>
"""));
var snap = idx.Get("p");
snap.StatusCode.ShouldBe(Good);
snap.Value.ShouldBe(string.Empty);
}
/// <summary>A structured observation with no text stays BadNotSupported — it never becomes a Good "" (#824).</summary>
[Fact]
public void A_structured_observation_with_no_text_stays_BadNotSupported()
{
var idx = new MTConnectObservationIndex([Tag("x", DriverDataType.String)]);
idx.Apply(Synthetic("x", "", isStructured: true));
idx.Get("x").StatusCode.ShouldBe(BadNotSupported);
}
// -------------------------------------------------------------------------- unknown lookups
/// <summary>A dataItemId that is neither authored nor ever observed is unknown to this driver.</summary>
@@ -1,22 +1,17 @@
// Unit tests for TwinCATDriverProbe — the degrade-guarded ADS ReadState Test-Connect probe.
// Unit tests for TwinCATDriverProbe — the ADS ReadState Test-Connect probe (#863).
//
// Coverage here is the set of outcomes that are *deterministic on a CI/dev box with no TwinCAT
// runtime*: invalid JSON, missing host/port, an unreachable TCP target, and — the crux — the
// DEGRADE path. On this box there is no AMS router, so once the TCP preflight succeeds against a
// reachable listener the managed ADS client cannot initialise (it throws a "Check for a running
// TwinCAT router instance!" server exception, NOT an ADS device rejection). The probe MUST treat
// that as "TCP reachability only" (Ok=true) so it never regresses below the old TCP-only probe.
//
// The two paths that REQUIRE a live ADS target are LIVE-VERIFY DEFERRED (no TwinCAT runtime on the
// rig): (a) the happy "ADS state: Run/Config/Stop" path (Ok=true with the AdsState name), and
// (b) the route/auth-reject RED path (a reachable router that refuses the route, surfaced as an
// AdsErrorException carrying a TargetPortNotFound / route AdsErrorCode → Ok=false with the
// "check the target's ADS route table" message). Those are exercised against a real TwinCAT XAR /
// remote runtime, out of scope for this unit suite.
// The probe takes exactly the driver's path: AdsClient.Connect(netId, port) through the LOCAL AMS
// router, then one ReadStateAsync. It must never open a socket of its own, and never to a host derived
// from the AMS Net ID (the old first-phase check dialled the Net ID's first four octets on the AMS
// port — an unrelated host, often a public one, on a port ADS does not use — so Test Connect timed out
// against every real runtime). The classification and budget tests drive the handshake through the
// internal seam; the no-dial and no-router tests use the real AdsClient on a box with no AMS router.
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Shouldly;
using TwinCAT.Ads;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests;
@@ -24,199 +19,162 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests;
[Trait("Category", "Unit")]
public sealed class TwinCATDriverProbeTests
{
private static readonly TwinCATDriverProbe Probe = new();
private const string Z35474Like = "{\"devices\":[{\"hostAddress\":\"ads://5.118.56.93.1.1:851\"}]}";
// -------------------------------------------------------------------------
// 1. Invalid JSON
// -------------------------------------------------------------------------
private static TwinCATDriverProbe ProbeWith(Func<TwinCATAmsAddress, TimeSpan, CancellationToken, Task<AdsState>> handshake)
=> new(handshake);
// ---- config validation ----------------------------------------------------------------
/// <summary>Invalid JSON returns Ok=false with a message containing "invalid".</summary>
[Fact]
public async Task InvalidJson_Returns_OkFalse_WithInvalidMessage()
{
var result = await Probe.ProbeAsync(
"not-valid-json{{{",
TimeSpan.FromSeconds(3),
TestContext.Current.CancellationToken);
var result = await new TwinCATDriverProbe().ProbeAsync(
"not-valid-json{{{", TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Message.ShouldNotBeNull();
result.Message!.ToLowerInvariant().ShouldContain("invalid");
result.Latency.ShouldBeNull();
}
// -------------------------------------------------------------------------
// 2. Config with no device / no host
// -------------------------------------------------------------------------
/// <summary>An empty Devices list returns Ok=false with a "no host/port" message.</summary>
[Fact]
public async Task NoDevices_Returns_OkFalse_WithNoHostPortMessage()
[Theory]
[InlineData("{\"devices\":[]}")]
[InlineData("{\"devices\":[{\"hostAddress\":\"not-an-ads-url\"}]}")]
public async Task NoUsableDevice_Returns_OkFalse_WithNoHostPortMessage(string json)
{
var result = await Probe.ProbeAsync(
"{\"devices\":[]}",
TimeSpan.FromSeconds(3),
TestContext.Current.CancellationToken);
var called = false;
var result = await ProbeWith((_, _, _) => { called = true; return Task.FromResult(AdsState.Run); })
.ProbeAsync(json, TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Message.ShouldNotBeNull();
result.Message!.ShouldContain("no host/port");
result.Latency.ShouldBeNull();
called.ShouldBeFalse();
}
/// <summary>
/// A first device with a malformed (non-<c>ads://</c>) host address returns Ok=false with a
/// "no host/port" message because <see cref="TwinCATAmsAddress.TryParse"/> returns null.
/// </summary>
[Fact]
public async Task MalformedHostAddress_Returns_OkFalse_WithNoHostPortMessage()
{
var result = await Probe.ProbeAsync(
"{\"devices\":[{\"hostAddress\":\"not-an-ads-url\"}]}",
TimeSpan.FromSeconds(3),
TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Message.ShouldNotBeNull();
result.Message!.ShouldContain("no host/port");
result.Latency.ShouldBeNull();
}
// -------------------------------------------------------------------------
// 3. Unreachable target — TCP preflight fails first
// -------------------------------------------------------------------------
// ---- #863: never dial a host derived from the AMS Net ID --------------------------------
/// <summary>
/// A closed port causes the TCP preflight <c>ConnectAsync</c> to throw
/// <see cref="SocketException"/>; the probe returns Ok=false with "Connect failed".
/// The port is reserved then released so the OS refuses the connection immediately.
/// Regression for #863. A listener sits on exactly the endpoint the old probe dialled
/// (Net ID octets 1–4 as IPv4, AMS port as TCP port). The real probe must never connect to
/// it — the old TCP pre-check connected here first, so this fails on the old behaviour.
/// </summary>
[Fact]
public async Task ClosedPort_Returns_OkFalse_WithConnectFailedMessage()
public async Task Probe_NeverConnects_ToAmsNetIdDerivedEndpoint()
{
// Reserve an ephemeral port then release it so the port is definitely closed.
var reserved = new TcpListener(IPAddress.Loopback, 0);
reserved.Start();
var port = ((IPEndPoint)reserved.LocalEndpoint).Port;
reserved.Stop();
// 127.0.0.1 as the first four AMS-Net-ID octets → the probe's TCP target is 127.0.0.1.
var configJson = $"{{\"devices\":[{{\"hostAddress\":\"ads://127.0.0.1.1.1:{port}\"}}]}}";
using var cts = CancellationTokenSource.CreateLinkedTokenSource(
TestContext.Current.CancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(5));
var result = await Probe.ProbeAsync(
configJson,
TimeSpan.FromSeconds(3),
cts.Token);
result.Ok.ShouldBeFalse();
result.Message.ShouldNotBeNull();
// Either a fast SocketException ("Connect failed") or, if the OS stalls, a timeout.
var lower = result.Message!.ToLowerInvariant();
(lower.Contains("connect failed") || lower.Contains("timed out")).ShouldBeTrue(
$"Expected 'Connect failed' or 'timed out' but got: {result.Message}");
result.Latency.ShouldBeNull();
}
/// <summary>
/// A target on a non-routable IP (192.0.2.1 — TEST-NET-1, RFC 5737) with a short
/// cancellation window times out (or fails fast on EHOSTUNREACH) at the TCP preflight.
/// </summary>
[Fact]
public async Task BlackHoleTarget_Returns_OkFalse_WithTimedOutOrConnectFailed()
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(
TestContext.Current.CancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(1));
var configJson = "{\"devices\":[{\"hostAddress\":\"ads://192.0.2.1.1.1:851\"}]}";
var result = await Probe.ProbeAsync(
configJson,
TimeSpan.FromSeconds(1),
cts.Token);
result.Ok.ShouldBeFalse();
result.Message.ShouldNotBeNull();
var lower = result.Message!.ToLowerInvariant();
(lower.Contains("timed out") || lower.Contains("connect failed")).ShouldBeTrue(
$"Expected 'timed out' or 'Connect failed' but got: {result.Message}");
result.Latency.ShouldBeNull();
}
// -------------------------------------------------------------------------
// 4. DEGRADE path — TCP reachable, but the ADS handshake can't be attempted here
// -------------------------------------------------------------------------
/// <summary>
/// The crux. A reachable TCP listener satisfies the preflight, but on this box (no TwinCAT
/// AMS router) the managed ADS client cannot establish a session — <c>AdsClient.Connect</c>
/// throws an environment/router exception (NOT an ADS device rejection). The probe MUST
/// DEGRADE: <c>Ok=true</c> with the "TCP reachability only" note, never a false RED. This
/// guarantees the new probe never reports worse than the old TCP-only probe on a host with
/// no ADS runtime.
/// </summary>
[Fact]
public async Task ReachableTcp_NoAdsRuntime_Degrades_To_OkTrue_WithTcpOnlyNote()
{
// Stand up a real TCP listener and accept (then drop) connections so the preflight
// ConnectAsync succeeds. We never speak ADS — the ADS handshake is what must degrade.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
using var acceptCts = CancellationTokenSource.CreateLinkedTokenSource(
TestContext.Current.CancellationToken);
var acceptLoop = Task.Run(async () =>
{
try
{
while (true)
{
var client = await listener.AcceptTcpClientAsync(acceptCts.Token);
// Hold the socket briefly so the preflight sees a clean accept, then close.
_ = Task.Run(async () =>
{
await Task.Delay(200);
client.Dispose();
});
}
}
catch (OperationCanceledException) { /* accept cancelled — expected on teardown */ }
catch (ObjectDisposedException) { /* listener stopped — expected on teardown */ }
catch (SocketException) { /* listener stopped — expected on teardown */ }
}, TestContext.Current.CancellationToken);
try
{
var configJson = $"{{\"devices\":[{{\"hostAddress\":\"ads://127.0.0.1.1.1:{port}\"}}]}}";
using var cts = CancellationTokenSource.CreateLinkedTokenSource(
TestContext.Current.CancellationToken);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(10));
await new TwinCATDriverProbe().ProbeAsync(
$"{{\"devices\":[{{\"hostAddress\":\"ads://127.0.0.1.1.1:{port}\"}}]}}",
TimeSpan.FromSeconds(3), cts.Token);
var result = await Probe.ProbeAsync(
configJson,
TimeSpan.FromSeconds(3),
cts.Token);
// DEGRADE guard: must be Ok=true (never worse than TCP-only), with the explicit note
// and a latency. If on some box AdsClient instead threw synchronously at construction,
// the probe still degrades the same way — this assertion holds either way.
result.Ok.ShouldBeTrue(
$"Degrade guard violated — probe returned a worse-than-TCP result: {result.Message}");
result.Message.ShouldNotBeNull();
result.Message!.ShouldContain("ADS handshake unavailable on this host");
result.Message!.ShouldContain("TCP reachability only");
result.Latency.ShouldNotBeNull();
listener.Pending().ShouldBeFalse(
"the probe opened a TCP connection to the AmsNetId-derived address — it must only use the local AMS router");
}
finally
{
await acceptCts.CancelAsync();
listener.Stop();
try { await acceptLoop; } catch { /* ignore teardown races */ }
}
}
/// <summary>The handshake receives the AMS address unchanged — the probe resolves no host itself.</summary>
[Fact]
public async Task Handshake_IsHandedTheAmsAddress_Unchanged()
{
TwinCATAmsAddress? seen = null;
var result = await ProbeWith((t, _, _) => { seen = t; return Task.FromResult(AdsState.Run); })
.ProbeAsync(Z35474Like, TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
result.Ok.ShouldBeTrue();
seen.ShouldBe(new TwinCATAmsAddress("5.118.56.93.1.1", 851));
}
// ---- outcome classification -------------------------------------------------------------
[Fact]
public async Task ReadStateOk_Returns_OkTrue_WithStateAndLatency()
{
var result = await ProbeWith((_, _, _) => Task.FromResult(AdsState.Run))
.ProbeAsync(Z35474Like, TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
result.Ok.ShouldBeTrue();
result.Message.ShouldBe("ADS state: Run");
result.Latency.ShouldNotBeNull();
}
/// <summary>
/// On a box with no AMS router the real AdsClient cannot connect. That is a RED naming the
/// missing router — no longer a green "TCP reachability only", since nothing was contacted.
/// </summary>
[Fact]
public async Task NoLocalRouter_RealClient_Returns_OkFalse_NamingTheRouter()
{
var result = await new TwinCATDriverProbe().ProbeAsync(
Z35474Like, TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Message!.ShouldContain("No local AMS router");
result.Message!.ShouldContain("not contacted");
result.Latency.ShouldBeNull();
}
[Fact]
public async Task AmsServerException_Classified_AsNoLocalRouter()
{
var result = await ProbeWith((_, _, _) => throw new global::TwinCAT.Ams.AmsServerException("Connect to Server failed!"))
.ProbeAsync(Z35474Like, TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Message!.ShouldContain("No local AMS router");
}
[Theory]
[InlineData(AdsErrorCode.ClientPortNotOpen, "No local AMS router")]
[InlineData(AdsErrorCode.TargetMachineNotFound, "No route to 5.118.56.93.1.1:851 or target unreachable")]
[InlineData(AdsErrorCode.TargetPortNotFound, "No route to 5.118.56.93.1.1:851 or target unreachable")]
[InlineData(AdsErrorCode.WSA_HostUnreachable, "No route to 5.118.56.93.1.1:851 or target unreachable")]
[InlineData(AdsErrorCode.ClientSyncTimeOut, "timed out")]
[InlineData(AdsErrorCode.DeviceInvalidGroup, "ADS handshake with 5.118.56.93.1.1:851 failed")]
public async Task AdsErrorCodes_AreClassified(AdsErrorCode code, string expected)
{
var result = await ProbeWith((_, _, _) => throw new AdsErrorException("x", code))
.ProbeAsync(Z35474Like, TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Message!.ShouldContain(expected);
result.Message!.ShouldContain(code.ToString());
result.Latency.ShouldBeNull();
}
// ---- time budget --------------------------------------------------------------------------
/// <summary>A handshake that never returns (and ignores its token) is cut off at the budget.</summary>
[Fact]
public async Task HangingHandshake_IsBoundedByTimeout()
{
var never = new TaskCompletionSource<AdsState>();
var sw = Stopwatch.StartNew();
var result = await ProbeWith((_, _, _) => never.Task)
.ProbeAsync(Z35474Like, TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken);
sw.Stop();
result.Ok.ShouldBeFalse();
result.Message!.ShouldContain("timed out after 1s");
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(5));
}
[Fact]
public async Task CallerCancellation_Returns_TimedOut()
{
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
var result = await ProbeWith(async (_, _, ct) => { await Task.Delay(Timeout.Infinite, ct); return AdsState.Run; })
.ProbeAsync(Z35474Like, TimeSpan.FromSeconds(10), cts.Token);
result.Ok.ShouldBeFalse();
result.Message!.ShouldContain("Probe timed out after 10s");
}
}