diff --git a/docs/drivers/MTConnect.md b/docs/drivers/MTConnect.md index d79624288..6cfd99839 100644 --- a/docs/drivers/MTConnect.md +++ b/docs/drivers/MTConnect.md @@ -678,7 +678,7 @@ deliberately different, kept. | Component nesting bound 64 (`MAX_COMPONENT_DEPTH`) | covered | `MTConnectProbeParser.MaxComponentDepth` · `MTConnectProbeParseTests` | | Streams element nesting bound 64 (`MAX_ELEMENT_DEPTH`) | **gap → closed** — the walk recursed without bound: an uncatchable `StackOverflowException`, i.e. a server-process crash | `MTConnectStreamsParser.MaxElementDepth` · `Streams_parse_refuses_absurd_nesting_…`, controls `Streams_parse_accepts_ordinary_device_nesting`, `An_absurdly_deep_error_document_still_yields_the_agents_words` | | Structural elements under ``/`` skipped (`NOT_A_COMPONENT`) | **gap → closed** (one stray `` failed the whole probe) | `MTConnectProbeParser.ComponentLikeChildren` · `A_structural_element_under_components_or_devices_is_skipped_not_fatal` | -| Malformed XML, missing header, missing `dataItemId` throw | covered | `Probe_parse_throws_on_malformed_xml`, `Parse_throws_on_malformed_xml`, `Parse_throws_on_a_malformed_observation` | +| Malformed XML and a missing/unusable `
` throw; a malformed OBSERVATION (no `dataItemId`, no/unparseable `timestamp`) is **skipped + counted** (#989 M-8 — it used to throw, so one bad adapter item failed every chunk, re-baseline and finally `InitializeAsync`; `MTConnectStreamsResult.SkippedObservations`/`FirstSkipReason`, one Warning per client) | covered | `Probe_parse_throws_on_malformed_xml`, `Parse_throws_on_malformed_xml`, `Parse_skips_a_malformed_observation_and_keeps_the_rest_of_the_document`, `CurrentAsync_survives_one_malformed_observation_and_warns_once` | | BOM / framing whitespace tolerated on a chunk | covered | `Parse_from_bytes_tolerates_the_multipart_frames_trailing_line_break` | | Multipart framing: Content-length authoritative, boundary-scan fallback, preamble, LF-only, split reads, truncation throws, 32 MiB part cap (`MTConnectMultipartReader`) | covered | `MultipartStreamReader` · `SampleAsync_frames_*`, `A_part_without_content_length_warns_once…`; Java cases ported as `A_declared_content_length_is_authoritative…`, `A_preamble_is_skipped_and_line_feed_only_framing_is_accepted`, `A_part_shorter_than_its_declared_content_length_is_a_lost_stream`, `A_part_larger_than_the_buffer_cap_is_refused` | | Typed Device → Component → DataItem tree; `name` else `id`; leaf ref = DataItem id (`MTConnectBrowseTree`) | covered | `DiscoverAsync`/`StreamContainer` · `MTConnectDiscoverTests` | @@ -834,6 +834,24 @@ NodeIds moved together in every leg. Fixture containers were restored healthy af | Genuine buffer overrun | A stalling TCP proxy froze the driver's transport while 32 000 observations were injected (`AllowPut`) — the Agent's `firstSequence` passed the driver's cursor (75 856 → 77 083). On release the resume was refused `OUT_OF_RANGE`, the driver re-baselined from `/current` within 1 s and resumed; values Good, no restart misdiagnosed. A raised-count stream (count 16, interval 5 s) was **not** lapped by a 266 obs/s burst: chunks are sent back-to-back while data is pending, so `interval` does not cap throughput. | | `SampleCount` vs `bufferSize` (#825) | Test Connect rendered the amber "OK with warning" chip and a deploy logged the Warning (`/hosts` shows `agentBufferSize`). The same gate measured the Agent's real edge — `count = 16384` streams, `16385` is `OUT_OF_RANGE` — so the first build's "at or above" threshold was corrected to "above" (pinned live by `Test_Connect_warns_when_SampleCount_exceeds_the_live_agents_buffer_size`). | +## Review 2026-12-02 fixes (#989) + +- **M-4 — condition word on a value tag.** Worst-of-states (Fault beats Warning beats Normal) applies only to a `/current` + baseline, where several states are simultaneously active, and only to CONDITION observations. A `/sample` chunk is a + time-ordered delta, so it is last-wins: Fault then Normal reads Normal, Fault then UNAVAILABLE reads + `BadNoCommunication`. (The native-alarm path never had the problem — `MTConnectConditionTracker`.) +- **M-5 — subscription leak.** `ShutdownAsync` releases every data and alarm subscription. The host actor abandons its + handles on each reconnect/Force Reconnect and re-subscribes after the next init, so the old registrations used to pile up + (one per cycle: an extra callback per observation and a pump that never stopped). `InitializeAsync` deliberately does + not clear (subscribe-before-initialize is a contract) and `ReinitializeAsync` keeps standing subscriptions. +- **M-7 — read-path restart.** A `ReadAsync` that sees a new Agent `instanceId` with no pump running re-baselines the + shared index and condition tracker from that `/current` (it already advanced the cursor, so no pump chunk would). +- **M-9 — initial replay.** After raising the initial replay, `SubscribeAsync` re-reads the index and re-raises anything + the pump pushed meanwhile (bounded), so a late stale replay cannot leave the node on an old value. (The MQTT half of M-9 + is tracked separately.) +- **M-10 — unsubscribe vs subscribe.** The stream stop re-checks for subscribers in the same critical section that + detaches the pump, so a concurrent subscribe keeps its pump. + ## Known limitations These are real, not placeholders — read them before relying on the driver diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectAgentClient.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectAgentClient.cs index 4d604a09c..747878e0a 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectAgentClient.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectAgentClient.cs @@ -211,6 +211,24 @@ public sealed class MTConnectAgentClient : IMTConnectAgentClient, IDisposable } } + private int _skippedObservationWarned; + + /// + /// M-8: the parser drops a malformed observation instead of failing the document; say so once per client (the + /// same item repeats in every /current and chunk, so a per-document warning would flood the log). + /// + 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; + } + /// public async Task 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)); } /// @@ -307,7 +325,7 @@ public sealed class MTConnectAgentClient : IMTConnectAgentClient, IDisposable delivered++; - yield return MTConnectStreamsParser.Parse(part); + yield return WarnOnSkipped(MTConnectStreamsParser.Parse(part)); } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDriver.Alarms.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDriver.Alarms.cs index 05e2e85c5..76e4ce8d0 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDriver.Alarms.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDriver.Alarms.cs @@ -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); } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDriver.cs index b1529c9e6..9096734db 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDriver.cs @@ -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 } } + /// + /// 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 Get, and would otherwise always look "moved". + /// + private static bool SameObservation(DataValueSnapshot a, DataValueSnapshot b) => + ReferenceEquals(a, b) || + (a.StatusCode == b.StatusCode && a.SourceTimestampUtc == b.SourceTimestampUtc && Equals(a.Value, b.Value)); + + /// + /// 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. + /// + internal Action? UnsubscribeGapHook { get; set; } + + /// Forgets every data and alarm subscription (see the M-5 note in ). + internal void ClearSubscriptions() + { + lock (_subscriptionLock) + { + _subscriptions.Clear(); + Volatile.Write(ref _alarmSubscription, null); + } + } + + /// The number of registered data subscriptions (test barrier for the M-5 leak). + internal int SubscriptionCount + { + get + { + lock (_subscriptionLock) + { + return _subscriptions.Count; + } + } + } + /// 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(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 } } + /// + /// M-7: replaces the shared index and condition tracker with as a fresh baseline, but only + /// while the session 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). + /// + 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); + } + } + /// /// The stream of the pump started under 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 /// /// /// The caller's deadline for the teardown wait. - private async Task StopSampleStreamAsync(CancellationToken cancellationToken = default) + /// + /// 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 LastSuccessfulRead frozen, so the watchdog never recovers it). + /// With this set the stop re-checks in the SAME critical section that + /// detaches the pump and does nothing when a subscriber has appeared. + /// + 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; diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDtos.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDtos.cs index 3a1b48c4c..ced51bccb 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDtos.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDtos.cs @@ -120,12 +120,19 @@ public sealed record MTConnectDataItem( /// document omits it. With it measures how far a /sample consumer is behind /// the Agent: LastSequence + 1 - NextSequence observations it has not been sent yet (R06:T-5). /// +/// +/// How many malformed observations (no dataItemId, no / unparseable timestamp) the parser dropped +/// rather than failing the whole document (M-8). Zero for a clean document. +/// +/// Why the first of them was dropped; null when none was. public sealed record MTConnectStreamsResult( long InstanceId, long NextSequence, long FirstSequence, IReadOnlyList Observations, - long? LastSequence = null); + long? LastSequence = null, + int SkippedObservations = 0, + string? FirstSkipReason = null); /// /// One observed value for a single DataItem, as reported in a /current snapshot or a diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectObservationIndex.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectObservationIndex.cs index 5e24da78f..9d04bb14f 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectObservationIndex.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectObservationIndex.cs @@ -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; /// - /// Picks the winner when one dataItemId appears more than once in a single document. A - /// <Condition> container legitimately carries several simultaneously active - /// states (a Fault and a Warning at once), so for a pair of recognized condition state words - /// the most severe 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. /// - /// Deliberately scoped to one document: a later 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. + /// /current (): a <Condition> container legitimately carries + /// several simultaneously active states (a Fault and a Warning at once), so for a pair of CONDITION + /// observations carrying recognized state words the most severe wins — plain last-wins would + /// under-report an active Fault as a Warning purely because of element order. + /// + /// + /// /sample (not ): 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 + /// Normal/Warning/Fault is last-wins in both modes. + /// + /// + /// Deliberately scoped to one document: a later 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. /// /// - 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; diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectStreamsParser.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectStreamsParser.cs index 4c0827416..5bb9ddf6c 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectStreamsParser.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectStreamsParser.cs @@ -309,7 +309,7 @@ internal static class MTConnectStreamsParser throw MTConnectXml.UnexpectedRoot((XElement)XNode.ReadFrom(reader), "MTConnectStreams", Subject); } - var observations = new List(); + 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); } /// @@ -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; + } + + /// The observation list, carrying what the parse skipped (M-8). + private sealed class ObservationList : List + { + public int Skipped { get; private set; } + + public string? FirstReason { get; private set; } + + public void NoteSkipped(string reason) + { + Skipped++; + FirstReason ??= reason; + } } /// diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectObservationIndexTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectObservationIndexTests.cs index bb8a0b6e3..cd0503328 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectObservationIndexTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectObservationIndexTests.cs @@ -756,13 +756,76 @@ public sealed class MTConnectObservationIndexTests [new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]); idx.Apply(new MTConnectStreamsResult(1L, 3L, 1L, [ - new MTConnectObservation("c", first, new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)), - new MTConnectObservation("c", second, new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)), - ])); + Cond("c", first, new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)), + Cond("c", second, new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)), + ]), baseline: true); idx.Get("c").Value.ShouldBe(expected); } + private static MTConnectObservation Cond(string id, string state, DateTime at) => + new(id, state, at, Condition: new MTConnectConditionDetail(null, null, null, null, null)); + + /// + /// M-4. A /sample chunk is a time-ordered delta: Fault then Normal for one id is a CLEARED fault. Worst-of used + /// to latch "Fault" (Good) until the item's next observation, possibly hours. + /// + [Theory] + [InlineData("Fault", "Normal", "Normal")] + [InlineData("Warning", "Normal", "Normal")] + [InlineData("Normal", "Fault", "Fault")] + [InlineData("Fault", "Warning", "Warning")] + public void A_sample_chunk_is_last_wins_for_condition_states(string first, string second, string expected) + { + var idx = new MTConnectObservationIndex( + [new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]); + + idx.Apply(new MTConnectStreamsResult(1L, 3L, 1L, [ + Cond("c", first, new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)), + Cond("c", second, new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)), + ])); + + var snap = idx.Get("c"); + snap.StatusCode.ShouldBe(Good); + snap.Value.ShouldBe(expected); + } + + /// M-4. Fault then UNAVAILABLE in one chunk is no-comms, not a Good "Fault". + [Fact] + public void A_sample_chunk_fault_then_unavailable_reads_no_communication() + { + var idx = new MTConnectObservationIndex( + [new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]); + + idx.Apply(new MTConnectStreamsResult(1L, 3L, 1L, [ + Cond("c", "Fault", new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)), + Cond("c", "UNAVAILABLE", new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)), + ])); + + idx.Get("c").StatusCode.ShouldBe(BadNoCommunication); + } + + /// + /// M-4 positive control + gate: the same pair as a baseline still keeps the worst, and an EVENT (no Condition + /// detail) whose text reads like a state word is last-wins even in a baseline. + /// + [Fact] + public void Worst_of_still_applies_to_a_baseline_but_never_to_an_event_whose_text_looks_like_a_state() + { + var idx = new MTConnectObservationIndex( + [new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION"), Tag("e", DriverDataType.String)]); + + idx.Apply(new MTConnectStreamsResult(1L, 3L, 1L, [ + Cond("c", "Fault", new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)), + Cond("c", "Normal", new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)), + new MTConnectObservation("e", "Fault", new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)), + new MTConnectObservation("e", "Normal", new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)), + ]), baseline: true); + + idx.Get("c").Value.ShouldBe("Fault"); + idx.Get("e").Value.ShouldBe("Normal"); + } + /// An active fault carries more information than "no value"; it outranks UNAVAILABLE. [Fact] public void An_active_fault_outranks_unavailable_within_one_apply() @@ -771,9 +834,9 @@ public sealed class MTConnectObservationIndexTests [new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]); idx.Apply(new MTConnectStreamsResult(1L, 3L, 1L, [ - new MTConnectObservation("c", "UNAVAILABLE", new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)), - new MTConnectObservation("c", "Fault", new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)), - ])); + Cond("c", "UNAVAILABLE", new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)), + Cond("c", "Fault", new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)), + ]), baseline: true); var snap = idx.Get("c"); diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectReview20261202Tests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectReview20261202Tests.cs new file mode 100644 index 000000000..94504647a --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectReview20261202Tests.cs @@ -0,0 +1,235 @@ +using System.Collections.Concurrent; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests; + +/// +/// Regression tests for the 2026-12-02 review's MTConnect findings (#989): M-5 subscription leak, M-7 read-path +/// restart re-baseline, M-9 stale initial replay, M-10 unsubscribe/subscribe race. (M-4 lives in +/// MTConnectObservationIndexTests, M-8 in MTConnectStreamsParseTests.) +/// +public sealed class MTConnectReview20261202Tests +{ + private const long FixtureInstanceId = 1655000000L; + private const long RestartedInstanceId = 1655999999L; + private const long PrimedNextSequence = 108L; + private const uint Good = 0x00000000u; + private const uint BadNoCommunication = 0x80310000u; + + private static readonly TimeSpan Watchdog = TimeSpan.FromSeconds(10); + private static readonly DateTime ObservedAt = new(2026, 7, 24, 12, 30, 0, DateTimeKind.Utc); + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static MTConnectDriverOptions Opts() => + new() + { + AgentUri = "http://fixture-agent:5000", + RequestTimeoutMs = 5000, + Tags = + [ + new MTConnectTagDefinition("dev1_pos", DriverDataType.Float64), + new MTConnectTagDefinition("dev1_execution", DriverDataType.String), + ], + }; + + private static MTConnectStreamsResult Chunk( + long instanceId, long first, long next, params (string Id, string Value)[] observations) => + new(instanceId, next, first, [.. observations.Select(o => new MTConnectObservation(o.Id, o.Value, ObservedAt))]); + + private static ConcurrentQueue Record(MTConnectDriver driver) + { + var seen = new ConcurrentQueue(); + driver.OnDataChange += (_, e) => seen.Enqueue(e); + + return seen; + } + + /// + /// M-5. The host actor drops its handle on every reconnect WITHOUT unsubscribing and subscribes afresh after the + /// next init, so a driver that keeps the old registration leaks one per cycle (an extra callback per + /// observation, and a pump that never stops). After ten cycles exactly one registration remains and one chunk + /// reaches the new handle exactly once. + /// + [Fact] + public async Task Shutdown_releases_every_subscription_so_reconnect_cycles_do_not_leak() + { + CannedAgentClient? latest = null; + var driver = new MTConnectDriver(Opts(), "mt1", _ => latest = CannedAgentClient.FromFixtures()); + var seen = Record(driver); + + await driver.InitializeAsync("{}", Ct); + + // What the actor does on a Connected -> Reconnecting: abandon the handle, shut down, re-init. + for (var cycle = 0; cycle < 10; cycle++) + { + await driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct); + await driver.ShutdownAsync(Ct).WaitAsync(Watchdog, Ct); + driver.SubscriptionCount.ShouldBe(0); + await driver.InitializeAsync("{}", Ct); + } + + // Positive control: the registry is not simply broken - a fresh subscribe works and gets the chunk once. + var handle = await driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct); + driver.SubscriptionCount.ShouldBe(1); + seen.Clear(); + + await latest!.PumpAsync(Chunk(FixtureInstanceId, PrimedNextSequence, 113, ("dev1_pos", "1.5"))) + .WaitAsync(Watchdog, Ct); + + var delivered = seen.Where(e => e.FullReference == "dev1_pos").ToList(); + delivered.Count.ShouldBe(1); + delivered[0].SubscriptionHandle.ShouldBe(handle); + delivered[0].Snapshot.Value.ShouldBe(1.5d); + + await driver.ShutdownAsync(Ct); + } + + /// M-5: the alarm slot is released by shutdown too, so a stopped driver does not pin a pump request. + [Fact] + public async Task Shutdown_releases_the_alarm_subscription() + { + var driver = new MTConnectDriver(Opts(), "mt1", _ => CannedAgentClient.FromFixtures()); + await driver.InitializeAsync("{}", Ct); + await driver.SubscribeAlarmsAsync(["some/condition"], Ct); + + await driver.ShutdownAsync(Ct).WaitAsync(Watchdog, Ct); + await driver.InitializeAsync("{}", Ct); + + // A subscribed alarm reference would restart the pump on init; none may. + driver.SampleStreamTask.ShouldBeNull(); + + await driver.ShutdownAsync(Ct); + } + + /// + /// M-7. With no pump running, a read that sees the Agent restart used to advance the session cursor to the new + /// instance without re-baselining the shared index, so the next subscribe replayed the dead process's value + /// as Good. + /// + [Fact] + public async Task A_read_that_sees_an_agent_restart_rebaselines_the_shared_index_for_the_next_subscribe() + { + var client = CannedAgentClient.FromFixtures(); + var driver = new MTConnectDriver(Opts(), "mt1", _ => client); + var seen = Record(driver); + await driver.InitializeAsync("{}", Ct); + + // Pre-condition (positive control): the primed index holds a Good value for dev1_pos. + (await driver.ReadAsync(["dev1_pos"], Ct))[0].StatusCode.ShouldBe(Good); + + // The Agent restarts (new instanceId) and now reports the item UNAVAILABLE. No subscription, so no pump. + client.Current = Chunk(RestartedInstanceId, 100, 200, ("dev1_pos", "UNAVAILABLE")); + driver.SampleStreamTask.ShouldBeNull(); + + (await driver.ReadAsync(["dev1_pos"], Ct))[0].StatusCode.ShouldBe(BadNoCommunication); + + await driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct); + + var initial = seen.Single(e => e.FullReference == "dev1_pos"); + initial.Snapshot.StatusCode.ShouldBe(BadNoCommunication); + initial.Snapshot.Value.ShouldBeNull(); + + await driver.ShutdownAsync(Ct); + } + + /// + /// M-9. The initial replay reads V1, the pump delivers V2 while a (slow) handler is still holding the replay, + /// then V1 is raised late: the node would stand on V1 until the item next changed. The last delivery must be + /// the cached V2. + /// + [Fact] + public async Task A_newer_pushed_value_is_not_overwritten_by_the_late_initial_replay() + { + var client = CannedAgentClient.FromFixtures(); + var driver = new MTConnectDriver(Opts(), "mt1", _ => client); + await driver.InitializeAsync("{}", Ct); + + var delivered = new ConcurrentQueue(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new ManualResetEventSlim(false); + var first = 0; + driver.OnDataChange += (_, e) => + { + if (Interlocked.Increment(ref first) == 1) + { + // The replay's V1: park the subscribing thread here while the pump pushes V2. + entered.TrySetResult(); + release.Wait(Watchdog); + } + + delivered.Enqueue(e.Snapshot.Value); + }; + + var subscribe = Task.Run( + () => driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct), Ct); + await entered.Task.WaitAsync(Watchdog, Ct); + + await client.PumpAsync(Chunk(FixtureInstanceId, PrimedNextSequence, 113, ("dev1_pos", "999.5"))) + .WaitAsync(Watchdog, Ct); + + release.Set(); + await subscribe.WaitAsync(Watchdog, Ct); + + delivered.Last().ShouldBe(999.5d); + + await driver.ShutdownAsync(Ct); + } + + /// + /// M-10. A subscribe landing between an unsubscribe's registry removal and its stream stop used to have its pump + /// cancelled by that stop, leaving a live subscriber with no stream (and health Healthy, so no watchdog). + /// + [Fact] + public async Task An_unsubscribe_does_not_stop_the_pump_a_concurrent_subscribe_relies_on() + { + var client = CannedAgentClient.FromFixtures(); + var driver = new MTConnectDriver(Opts(), "mt1", _ => client); + var seen = Record(driver); + await driver.InitializeAsync("{}", Ct); + + var a = await driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct); + await client.PumpAsync(Chunk(FixtureInstanceId, PrimedNextSequence, 113, ("dev1_pos", "1.5"))) + .WaitAsync(Watchdog, Ct); + + ISubscriptionHandle? b = null; + driver.UnsubscribeGapHook = () => + { + driver.UnsubscribeGapHook = null; + b = driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct).GetAwaiter().GetResult(); + }; + + await driver.UnsubscribeAsync(a, Ct).WaitAsync(Watchdog, Ct); + + b.ShouldNotBeNull(); + var pump = driver.SampleStreamTask.ShouldNotBeNull(); + pump.IsCompleted.ShouldBeFalse(); + + seen.Clear(); + await client.PumpAsync(Chunk(FixtureInstanceId, 113, 118, ("dev1_pos", "2.5"))).WaitAsync(Watchdog, Ct); + seen.Where(e => e.SubscriptionHandle == b && e.Snapshot.Value is 2.5d).ShouldNotBeEmpty(); + + await driver.ShutdownAsync(Ct); + } + + /// M-10 positive control: with no concurrent subscriber the last unsubscribe still stops the pump. + [Fact] + public async Task The_last_unsubscribe_still_stops_the_pump() + { + var client = CannedAgentClient.FromFixtures(); + var driver = new MTConnectDriver(Opts(), "mt1", _ => client); + await driver.InitializeAsync("{}", Ct); + + var a = await driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct); + var pump = driver.SampleStreamTask.ShouldNotBeNull(); + + await driver.UnsubscribeAsync(a, Ct).WaitAsync(Watchdog, Ct); + + pump.IsCompleted.ShouldBeTrue(); + driver.SampleStreamTask.ShouldBeNull(); + + await driver.ShutdownAsync(Ct); + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectStreamsParseTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectStreamsParseTests.cs index eba125ea4..e0ab62d19 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectStreamsParseTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/MTConnectStreamsParseTests.cs @@ -490,21 +490,100 @@ public sealed class MTConnectStreamsParseTests [InlineData("""1""")] // no dataItemId [InlineData("""1""")] // no timestamp [InlineData("""1""")] // unparseable timestamp - public void Parse_throws_on_a_malformed_observation(string observationXml) + public void Parse_skips_a_malformed_observation_and_keeps_the_rest_of_the_document(string observationXml) { - Should.Throw( - () => MTConnectStreamsParser.Parse(StreamsDocument($"{observationXml}"))); + // M-8: one bad observation used to throw out of the parse, so every chunk, every re-baseline and finally + // InitializeAsync failed for the whole driver. Now it is skipped + counted; the valid neighbours survive. + var result = MTConnectStreamsParser.Parse(StreamsDocument( + $"""1{observationXml}2""")); + + result.Observations.Select(o => o.DataItemId).ShouldBe(["a", "b"]); + result.SkippedObservations.ShouldBe(1); + result.FirstSkipReason.ShouldNotBeNullOrWhiteSpace(); + result.InstanceId.ShouldBe(1L); + } + + /// M-8 positive control: a clean document reports nothing skipped. + [Fact] + public void Parse_of_a_clean_document_reports_nothing_skipped() + { + var result = MTConnectStreamsParser.Parse(StreamsDocument( + """1""")); + + result.SkippedObservations.ShouldBe(0); + result.FirstSkipReason.ShouldBeNull(); + result.Observations.Count.ShouldBe(1); + } + + /// M-8: a malformed observation WITH nested content is consumed whole (cursor contract) — what follows it still parses. + [Fact] + public void Parse_skips_a_malformed_observation_that_has_children() + { + var result = MTConnectStreamsParser.Parse(StreamsDocument( + """x2""")); + + result.Observations.Select(o => o.DataItemId).ShouldBe(["b"]); + result.SkippedObservations.ShouldBe(1); + } + + /// M-8: the client lifts the same lenient parse — a /current with one bad observation returns the rest, warning once. + [Fact] + public async Task CurrentAsync_survives_one_malformed_observation_and_warns_once() + { + const string doc = """ + +
+ + + 1 + 2 + + + + """; + var logger = new CapturingClientLogger(); + using var client = new MTConnectAgentClient( + new MTConnectDriverOptions { AgentUri = "http://agent:5000" }, StubHandler.RespondingWith(doc), logger); + + var first = await client.CurrentAsync(Ct); + var second = await client.CurrentAsync(Ct); + + first.Observations.Select(o => o.DataItemId).ShouldBe(["b"]); + second.Observations.Select(o => o.DataItemId).ShouldBe(["b"]); + logger.Warnings.Count.ShouldBe(1); + } + + private sealed class CapturingClientLogger : Microsoft.Extensions.Logging.ILogger + { + public List Warnings { get; } = []; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true; + + public void Log( + Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, + Exception? exception, Func formatter) + { + if (logLevel == Microsoft.Extensions.Logging.LogLevel.Warning) + { + Warnings.Add(formatter(state, exception)); + } + } } [Fact] public void Parse_reads_only_unqualified_attributes() { // A prefixed x:dataItemId is a vendor extension, not the observation's identity — reading it - // would invent a data item that the probe never declared. + // would invent a data item that the probe never declared. (Since M-8 it is skipped, not fatal.) var xml = StreamsDocument( """1"""); - Should.Throw(() => MTConnectStreamsParser.Parse(xml)); + var result = MTConnectStreamsParser.Parse(xml); + + result.Observations.ShouldBeEmpty(); + result.SkippedObservations.ShouldBe(1); } // ------------------------------------------------------------- MTConnectAgentClient.CurrentAsync