Merge #989: MTConnect condition last-wins in /sample, subscription release on shutdown, restart re-baseline, parser skips bad observations, subscribe/unsubscribe races

This commit is contained in:
Joseph Doherty
2026-12-03 10:16:27 -05:00
10 changed files with 643 additions and 40 deletions
@@ -211,6 +211,24 @@ public sealed class MTConnectAgentClient : IMTConnectAgentClient, IDisposable
}
}
private int _skippedObservationWarned;
/// <summary>
/// M-8: the parser drops a malformed observation instead of failing the document; say so once per client (the
/// same item repeats in every <c>/current</c> and chunk, so a per-document warning would flood the log).
/// </summary>
private MTConnectStreamsResult WarnOnSkipped(MTConnectStreamsResult result)
{
if (result.SkippedObservations > 0 && Interlocked.Exchange(ref _skippedObservationWarned, 1) == 0)
{
_logger?.LogWarning(
"MTConnect Agent {AgentUri} sent {SkippedCount} malformed observation(s) in one document (first: {Reason}); they are skipped and the rest of the document is used. This is logged once per connection.",
MTConnectUriRedaction.Redact(_agentRoot), result.SkippedObservations, result.FirstSkipReason);
}
return result;
}
/// <inheritdoc/>
public async Task<MTConnectStreamsResult> CurrentAsync(CancellationToken ct)
{
@@ -220,7 +238,7 @@ public sealed class MTConnectAgentClient : IMTConnectAgentClient, IDisposable
await using var body = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
return MTConnectStreamsParser.Parse(body);
return WarnOnSkipped(MTConnectStreamsParser.Parse(body));
}
/// <inheritdoc/>
@@ -307,7 +325,7 @@ public sealed class MTConnectAgentClient : IMTConnectAgentClient, IDisposable
delivered++;
yield return MTConnectStreamsParser.Parse(part);
yield return WarnOnSkipped(MTConnectStreamsParser.Parse(part));
}
}
@@ -151,10 +151,12 @@ public sealed partial class MTConnectDriver : IAlarmSource, IAlarmInitialStateSi
stopStream = !HasSubscribedReferencesCore();
}
UnsubscribeGapHook?.Invoke();
if (stopStream)
{
// Outside the lock — see UnsubscribeAsync.
await StopSampleStreamAsync(cancellationToken).ConfigureAwait(false);
await StopSampleStreamAsync(cancellationToken, onlyIfIdle: true).ConfigureAwait(false);
}
}
@@ -669,6 +669,15 @@ public sealed partial class MTConnectDriver
await StopProbeLoopAsync(cancellationToken).ConfigureAwait(false);
await TeardownCoreAsync().ConfigureAwait(false);
// M-5: the host actor drops its handles on every Connected -> Reconnecting transition, Force Reconnect and
// respawn WITHOUT unsubscribing, then subscribes afresh after the next successful init. Left registered, each
// orphan costs a lookup + event + handler call per observation forever and keeps `HasSubscribedReferencesCore`
// true (so the pump never stops). A shutdown is the end of every subscription this driver issued; the
// restarted pump (re-baseline on init) has nobody to serve until the actor re-subscribes. Deliberately NOT
// done at the top of InitializeAsync/ReinitializeAsync: subscribe-before-initialize is a documented
// contract, and ReinitializeAsync keeps standing subscriptions by design.
ClearSubscriptions();
WriteHealth(new DriverHealth(DriverState.Unknown, lastRead, null));
}
finally
@@ -677,6 +686,42 @@ public sealed partial class MTConnectDriver
}
}
/// <summary>
/// Whether two snapshots of one item describe the same observation. The server timestamp is ignored: an item with
/// no value yet is re-synthesised (fresh stamp) on every <c>Get</c>, and would otherwise always look "moved".
/// </summary>
private static bool SameObservation(DataValueSnapshot a, DataValueSnapshot b) =>
ReferenceEquals(a, b) ||
(a.StatusCode == b.StatusCode && a.SourceTimestampUtc == b.SourceTimestampUtc && Equals(a.Value, b.Value));
/// <summary>
/// Test seam (M-10): runs between an unsubscribe's registry removal and its stream stop - the window a concurrent
/// subscribe used to be able to land in.
/// </summary>
internal Action? UnsubscribeGapHook { get; set; }
/// <summary>Forgets every data and alarm subscription (see the M-5 note in <see cref="ShutdownAsync"/>).</summary>
internal void ClearSubscriptions()
{
lock (_subscriptionLock)
{
_subscriptions.Clear();
Volatile.Write(ref _alarmSubscription, null);
}
}
/// <summary>The number of registered data subscriptions (test barrier for the M-5 leak).</summary>
internal int SubscriptionCount
{
get
{
lock (_subscriptionLock)
{
return _subscriptions.Count;
}
}
}
/// <inheritdoc/>
public DriverHealth GetHealth() => ReadHealth();
@@ -776,6 +821,12 @@ public sealed partial class MTConnectDriver
// spend its first chunk on a clear + re-baseline (a Bad flicker). Move it to the new process — through
// the same generation-checked publish the pump uses, so it can only land on the session this read used.
PublishAgentCursor(readGeneration, current.InstanceId, current.NextSequence);
// M-7: advancing the cursor means the next pump will open on the new instance with no gap, so its
// first chunk will NOT clear + re-baseline the shared index/tracker any more - they would keep the
// dead process's values for every item that never changes again. With no pump to do it, this read's
// /current IS the baseline: install it.
RebaselineSharedStateWithoutPump(readGeneration, current);
}
// Built from the SAME authored tags as the shared index, so the authored-vs-unknown
@@ -1291,9 +1342,37 @@ public sealed partial class MTConnectDriver
// behind it is translated to the DataItem id.
var index = ObservationIndex;
var binding = Volatile.Read(ref _binding);
var replayed = new Dictionary<string, DataValueSnapshot>(references.Count, StringComparer.Ordinal);
foreach (var reference in references)
{
RaiseDataChange(handle, reference, index.Get(binding.ToDataItemId(reference)));
var snapshot = index.Get(binding.ToDataItemId(reference));
replayed[reference] = snapshot;
RaiseDataChange(handle, reference, snapshot);
}
// M-9: the replay read V1, then the pump may have applied + raised V2 (the handle was already registered above)
// before this thread raised V1 - leaving the node on the stale V1 until the item next changes. Re-read once the
// replay is out and re-raise anything that moved underneath it; repeat (bounded) in case it moves again.
for (var pass = 0; pass < 3; pass++)
{
var moved = false;
foreach (var reference in references)
{
var latest = index.Get(binding.ToDataItemId(reference));
if (SameObservation(replayed[reference], latest))
{
continue;
}
moved = true;
replayed[reference] = latest;
RaiseDataChange(handle, reference, latest);
}
if (!moved)
{
break;
}
}
_logger.LogDebug(
@@ -1329,13 +1408,15 @@ public sealed partial class MTConnectDriver
stopStream = !HasSubscribedReferencesCore();
}
UnsubscribeGapHook?.Invoke();
if (stopStream)
{
// Outside the lock: StopSampleStreamAsync awaits the pump, and the pump takes this same
// lock to read the subscription registry. Holding it here would deadlock the two.
// The caller's token bounds the wait: DriverInstanceActor puts a 5 s budget around this
// call, and until now that budget was inert.
await StopSampleStreamAsync(cancellationToken).ConfigureAwait(false);
await StopSampleStreamAsync(cancellationToken, onlyIfIdle: true).ConfigureAwait(false);
}
_logger.LogDebug(
@@ -2812,6 +2893,29 @@ public sealed partial class MTConnectDriver
}
}
/// <summary>
/// M-7: replaces the shared index and condition tracker with <paramref name="current"/> as a fresh baseline, but only
/// while the session <paramref name="generation"/> is still installed AND no pump is running for it (a running pump
/// is the index's single writer and re-baselines itself on the restart it sees).
/// </summary>
private void RebaselineSharedStateWithoutPump(long generation, MTConnectStreamsResult current)
{
lock (_subscriptionLock)
{
if (_sessionGeneration != generation || _pumpTask is { IsCompleted: false })
{
return;
}
var index = Volatile.Read(ref _index);
var tracker = Volatile.Read(ref _conditions);
index.Clear();
tracker.Clear();
index.Apply(current, baseline: true);
tracker.Apply(current, baseline: true);
}
}
/// <summary>
/// The stream of the pump started under <paramref name="generation"/> failed: degrade it — under the generation
/// check, in one critical section, so a superseded pump's failure never lands on the session that replaced it.
@@ -3532,7 +3636,14 @@ public sealed partial class MTConnectDriver
/// </para>
/// </remarks>
/// <param name="cancellationToken">The caller's deadline for the teardown wait.</param>
private async Task StopSampleStreamAsync(CancellationToken cancellationToken = default)
/// <param name="onlyIfIdle">
/// M-10: the unsubscribe paths decide "nothing left to serve" under the lock, release it, and only then stop.
/// A subscribe landing in that gap sees a live pump, starts none, and the stop would cancel the very pump it
/// relied on (health stays Healthy with <c>LastSuccessfulRead</c> frozen, so the watchdog never recovers it).
/// With this set the stop re-checks <see cref="HasSubscribedReferencesCore"/> in the SAME critical section that
/// detaches the pump and does nothing when a subscriber has appeared.
/// </param>
private async Task StopSampleStreamAsync(CancellationToken cancellationToken = default, bool onlyIfIdle = false)
{
CancellationTokenSource? cts;
Task? task;
@@ -3540,6 +3651,11 @@ public sealed partial class MTConnectDriver
lock (_subscriptionLock)
{
if (onlyIfIdle && HasSubscribedReferencesCore())
{
return;
}
cts = _pumpCts;
task = _pumpTask;
_pumpCts = null;
@@ -120,12 +120,19 @@ public sealed record MTConnectDataItem(
/// document omits it. With <see cref="NextSequence"/> it measures how far a <c>/sample</c> consumer is behind
/// the Agent: <c>LastSequence + 1 - NextSequence</c> observations it has not been sent yet (R06:T-5).
/// </param>
/// <param name="SkippedObservations">
/// How many malformed observations (no <c>dataItemId</c>, no / unparseable <c>timestamp</c>) the parser dropped
/// rather than failing the whole document (M-8). Zero for a clean document.
/// </param>
/// <param name="FirstSkipReason">Why the first of them was dropped; <c>null</c> when none was.</param>
public sealed record MTConnectStreamsResult(
long InstanceId,
long NextSequence,
long FirstSequence,
IReadOnlyList<MTConnectObservation> Observations,
long? LastSequence = null);
long? LastSequence = null,
int SkippedObservations = 0,
string? FirstSkipReason = null);
/// <summary>
/// One observed value for a single DataItem, as reported in a <c>/current</c> snapshot or a
@@ -229,7 +229,7 @@ internal sealed class MTConnectObservationIndex
resolved[observation.DataItemId] =
resolved.TryGetValue(observation.DataItemId, out var incumbent)
? Reconcile(incumbent, observation)
? Reconcile(incumbent, observation, baseline)
: observation;
}
@@ -418,21 +418,32 @@ internal sealed class MTConnectObservationIndex
private DateTime Now => _timeProvider.GetUtcNow().UtcDateTime;
/// <summary>
/// Picks the winner when one dataItemId appears more than once in a single document. A
/// <c>&lt;Condition&gt;</c> container legitimately carries several <b>simultaneously active</b>
/// states (a Fault and a Warning at once), so for a pair of recognized condition state words
/// the <b>most severe</b> wins — plain last-wins would under-report an active Fault as a
/// Warning purely because of element order. Anything else is last-wins, matching the Agent's
/// ascending-sequence ordering.
/// Picks the winner when one dataItemId appears more than once in a single document.
/// <para>
/// Deliberately scoped to one document: a later <see cref="Apply"/> is the Agent's new
/// statement of the state, so a cleared fault must fall back to Normal. A worst-of that
/// spanned Applies would latch every fault forever.
/// <b>/current (<paramref name="baseline"/>)</b>: a <c>&lt;Condition&gt;</c> container legitimately carries
/// several <b>simultaneously active</b> states (a Fault and a Warning at once), so for a pair of CONDITION
/// observations carrying recognized state words the <b>most severe</b> wins — plain last-wins would
/// under-report an active Fault as a Warning purely because of element order.
/// </para>
/// <para>
/// <b>/sample (not <paramref name="baseline"/>)</b>: the chunk is a time-ordered delta, so the later
/// observation IS the state — a Fault at N then a Normal at N+1 is a cleared fault, and a Fault then
/// UNAVAILABLE is no-comms (M-4). Worst-of there latched "Fault" until the item's next observation.
/// Gated on the observation being a CONDITION: an EVENT whose text happens to read
/// <c>Normal</c>/<c>Warning</c>/<c>Fault</c> is last-wins in both modes.
/// </para>
/// <para>
/// Deliberately scoped to one document: a later <see cref="Apply"/> is the Agent's new statement of the
/// state, so a cleared fault must fall back to Normal. A worst-of that spanned Applies would latch every
/// fault forever.
/// </para>
/// </summary>
private static MTConnectObservation Reconcile(MTConnectObservation incumbent, MTConnectObservation challenger)
private static MTConnectObservation Reconcile(
MTConnectObservation incumbent, MTConnectObservation challenger, bool baseline)
{
if (ConditionSeverity.TryGetValue(incumbent.Value ?? string.Empty, out var incumbentSeverity) &&
if (baseline &&
incumbent.Condition is not null && challenger.Condition is not null &&
ConditionSeverity.TryGetValue(incumbent.Value ?? string.Empty, out var incumbentSeverity) &&
ConditionSeverity.TryGetValue(challenger.Value ?? string.Empty, out var challengerSeverity))
{
return challengerSeverity >= incumbentSeverity ? challenger : incumbent;
@@ -309,7 +309,7 @@ internal static class MTConnectStreamsParser
throw MTConnectXml.UnexpectedRoot((XElement)XNode.ReadFrom(reader), "MTConnectStreams", Subject);
}
var observations = new List<MTConnectObservation>();
var observations = new ObservationList();
HeaderSequences? header = null;
if (!reader.IsEmptyElement)
@@ -341,7 +341,9 @@ internal static class MTConnectStreamsParser
sequences.NextSequence,
sequences.FirstSequence,
observations,
sequences.LastSequence);
sequences.LastSequence,
observations.Skipped,
observations.FirstReason);
}
/// <summary>
@@ -415,8 +417,35 @@ internal static class MTConnectStreamsParser
if (isObservation)
{
var name = reader.LocalName;
dataItemId = MTConnectXml.RequiredAttribute(reader, "dataItemId", $"Observation <{name}>", Subject);
timestampUtc = ReadTimestampUtc(reader, dataItemId);
// M-8: one malformed observation (no dataItemId, no / unparseable timestamp) is skipped and counted,
// not fatal. /current repeats the same observation, so throwing here failed every chunk, every
// re-baseline and finally InitializeAsync - one bad adapter faulted the whole driver. Header / root
// problems still fail the document: without them the sequence bookkeeping is unknowable.
dataItemId = MTConnectXml.OptionalAttribute(reader, "dataItemId");
string? skipReason = null;
if (dataItemId is null)
{
skipReason = $"observation <{name}> has no 'dataItemId'";
}
else if (!TryReadTimestampUtc(reader, dataItemId, out timestampUtc, out skipReason))
{
// skipReason carries the explanation
}
if (skipReason is not null)
{
(observations as ObservationList)?.NoteSkipped(skipReason);
// Consume the subtree to honour the cursor contract (nothing inside a malformed observation is read).
if (!reader.IsEmptyElement)
{
ReadChildren(reader, ContainerKind.None, observations, null, null);
}
return;
}
conditionState = isCondition ? ConditionState(name) : null;
// A condition's alarm identity rides the element's attributes — read here, before the
@@ -628,9 +657,16 @@ internal static class MTConnectStreamsParser
private static string ConditionState(string localName) =>
string.Equals(localName, "Unavailable", StringComparison.OrdinalIgnoreCase) ? UnavailableSentinel : localName;
private static DateTime ReadTimestampUtc(XmlReader reader, string dataItemId)
private static bool TryReadTimestampUtc(XmlReader reader, string dataItemId, out DateTime utc, out string? problem)
{
var raw = MTConnectXml.RequiredAttribute(reader, "timestamp", $"Observation '{dataItemId}'", Subject);
utc = default;
var raw = MTConnectXml.OptionalAttribute(reader, "timestamp");
if (raw is null)
{
problem = $"observation '{dataItemId}' has no 'timestamp'";
return false;
}
if (!DateTime.TryParse(
raw,
@@ -638,13 +674,31 @@ internal static class MTConnectStreamsParser
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
out var parsed))
{
throw new InvalidDataException(
$"MTConnect streams response is malformed: observation '{dataItemId}' has an unparseable 'timestamp' ('{raw}').");
problem = $"observation '{dataItemId}' has an unparseable 'timestamp' ('{raw}')";
return false;
}
// AdjustToUniversal already yields Utc; stated explicitly so a future styles change cannot
// quietly hand the OPC UA layer a Local or Unspecified SourceTimestamp.
return DateTime.SpecifyKind(parsed, DateTimeKind.Utc);
utc = DateTime.SpecifyKind(parsed, DateTimeKind.Utc);
problem = null;
return true;
}
/// <summary>The observation list, carrying what the parse skipped (M-8).</summary>
private sealed class ObservationList : List<MTConnectObservation>
{
public int Skipped { get; private set; }
public string? FirstReason { get; private set; }
public void NoteSkipped(string reason)
{
Skipped++;
FirstReason ??= reason;
}
}
/// <summary>