fix(mtconnect): close Java-driver parity gaps found by the #804 review

- Lift an Agent's MTConnectError body under a non-2xx status (cppagent 2.x serves
  OUT_OF_RANGE as HTTP 400, NO_DEVICE as 404) into the refusal-marked
  InvalidDataException, reading at most 64 KiB. The 400 used to be a transport
  fault, so the OUT_OF_RANGE re-baseline never ran against a real 2.x Agent.
- Run the instanceId restart test on every re-baseline snapshot: on 2.x a restart
  is first seen there (the old cursor gets a 400), and was adopted silently.
- Report the stream Degraded after 3 consecutive re-baselines with no /sample
  chunk (it read Healthy for ever); LastSuccessfulRead keeps advancing.
- Prohibit DTDs on the /probe and write-answer parses; bound the streams walk to
  64 levels (unbounded recursion = uncatchable StackOverflowException).
- Skip structural elements under <Components>/<Devices> instead of failing the probe.
- Never serve a non-finite float as Good; serve integer-valued decimals on
  integral tags losslessly (a real fraction stays BadOutOfRange).
- Merge sibling browse containers that resolve to one folder name.

Unit 678 -> 714, integration 18 -> 20 (live fixture); every gap test failed first.
This commit is contained in:
Joseph Doherty
2026-11-10 23:08:42 -05:00
parent 308b1b3b56
commit d6392dae17
10 changed files with 1168 additions and 33 deletions
@@ -837,6 +837,116 @@ public sealed class MTConnectAgentIntegrationTests(MTConnectAgentFixture agent)
}
}
// ---- #804: the 2.x Agent's error documents under a non-2xx status ----
/// <summary>
/// #804 — a 2.x Agent answers a <c>from</c> outside its buffer with <b>HTTP 400</b> + <c>MTConnectError</c>
/// <c>OUT_OF_RANGE</c> (live-verified against this fixture). The client must surface it as the
/// <see cref="InvalidDataException"/> the pump re-baselines on; before #804 it was a bare
/// <see cref="HttpRequestException"/>, which the pump read as transport loss and reconnected at the same
/// evicted cursor — the documented OUT_OF_RANGE re-baseline never ran against a real 2.x Agent.
/// </summary>
[Fact(Timeout = TestTimeoutMs)]
public async Task A_sample_cursor_outside_the_buffer_is_the_agents_out_of_range_refusal()
{
SkipIfDown();
// A cursor the Agent cannot hold: far past its nextSequence. (An OLD cursor is not reliable here — a
// freshly restarted Agent may still hold sequence 1, and then the stream simply opens.)
var next = (long?)(await CurrentAsync()).Root?.Elements().FirstOrDefault(e => e.Name.LocalName == "Header")
?.Attribute("nextSequence") ?? 0L;
using var client = new MTConnectAgentClient(LiveOptions());
var ex = await Should.ThrowAsync<InvalidDataException>(async () =>
{
await foreach (var _ in client.SampleAsync(next + 1_000_000, Ct))
{
}
});
ex.Message.ShouldContain("OUT_OF_RANGE");
}
/// <summary>
/// #804 — a <c>SampleCount</c> at or above the Agent's <c>bufferSize</c> is refused <c>OUT_OF_RANGE</c> on
/// EVERY <c>/sample</c> open (live: <c>'count' must be less than N</c>). The driver keeps serving values off
/// <c>/current</c> re-baselines, and — after three in a row with no <c>/sample</c> chunk — reports the stream
/// Degraded with <c>LastSuccessfulRead</c> still advancing, rather than Healthy for ever (before #804 the
/// 400 was a transport fault: Degraded, but every value stuck at the priming <c>/current</c>).
/// </summary>
[Fact(Timeout = TestTimeoutMs)]
public async Task A_sample_count_the_agent_refuses_is_reported_degraded_while_values_keep_flowing()
{
SkipIfDown();
var bufferSize = (int?)agent.ProbeDocument?.Root?.Elements().FirstOrDefault(e => e.Name.LocalName == "Header")
?.Attribute("bufferSize");
if (bufferSize is not > 0)
{
Assert.Skip($"The Agent at {agent.AgentUri} declares no bufferSize in its /probe header.");
}
var ids = await NumericSampleIdsAsync();
if (ids.Count == 0)
{
Assert.Skip($"The Agent at {agent.AgentUri} is currently reporting no numeric SAMPLE value.");
}
var options = new MTConnectDriverOptions
{
AgentUri = agent.AgentUri,
RequestTimeoutMs = 15_000,
SampleIntervalMs = 200,
SampleCount = bufferSize.Value + 1,
HeartbeatMs = 5_000,
Probe = new MTConnectProbeOptions { Enabled = false },
Reconnect = new MTConnectReconnectOptions { MinBackoffMs = 0, MaxBackoffMs = 200 },
};
var driver = new MTConnectDriver(options, "mtconnect-live-oor");
await using var live = new LiveDriver(driver);
await driver.InitializeAsync(
JsonSerializer.Serialize(new
{
agentUri = options.AgentUri,
requestTimeoutMs = options.RequestTimeoutMs,
sampleIntervalMs = options.SampleIntervalMs,
sampleCount = options.SampleCount,
heartbeatMs = options.HeartbeatMs,
probe = new { enabled = false },
reconnect = new { minBackoffMs = 0, maxBackoffMs = 200, backoffMultiplier = 2.0 },
tags = ids.Select(id => new { fullName = id, driverDataType = "Float64" }),
}),
Ct);
var seen = new ConcurrentQueue<DataChangeEventArgs>();
driver.OnDataChange += (_, e) => seen.Enqueue(e);
await driver.SubscribeAsync([.. ids], TimeSpan.FromMilliseconds(200), Ct);
var deadline = DateTime.UtcNow + StreamWait;
while (driver.GetHealth().LastError != "repeated /sample re-baselines with no observations in between" &&
DateTime.UtcNow < deadline)
{
await Task.Delay(100, Ct);
}
var health = driver.GetHealth();
health.State.ShouldBe(DriverState.Degraded);
health.LastError.ShouldBe("repeated /sample re-baselines with no observations in between");
var stamp = health.LastSuccessfulRead.ShouldNotBeNull();
// Values keep flowing off the re-baselines: the stamp advances and Good values keep arriving.
var before = seen.Count;
deadline = DateTime.UtcNow + StreamWait;
while ((driver.GetHealth().LastSuccessfulRead <= stamp || seen.Count <= before) && DateTime.UtcNow < deadline)
{
await Task.Delay(100, Ct);
}
driver.GetHealth().State.ShouldBe(DriverState.Degraded);
driver.GetHealth().LastSuccessfulRead!.Value.ShouldBeGreaterThan(stamp);
seen.Skip(before).ShouldContain(e => e.Snapshot.StatusCode == Good);
}
private static bool Is(string? value, string expected) =>
string.Equals(value?.Trim(), expected, StringComparison.OrdinalIgnoreCase);