feat(mtconnect): read-only MTConnect Agent driver (P1) — 23 tasks + 5-leg live gate #506

Merged
dohertj2 merged 34 commits from feat/mtconnect-driver into master 2026-07-27 14:02:29 -04:00
Owner

Adds a read-only MTConnect Agent driver — the first of the seven curated next-drivers
(docs/plans/2026-07-24-driver-expansion-tracking.md). Executes
docs/plans/2026-07-24-mtconnect-driver.md end to end: all 23 tasks, plus a full 5-leg live
gate against a real MTConnect Agent.

Equipment-kind, no COM gateway. Capabilities: IReadable, ISubscribable, ITagDiscovery,
IHostConnectivityProbe, IRediscoverable. Deliberately not IWritable — MTConnect
write-back is a separate protocol surface, deferred with a note in docs/drivers/MTConnect.md.

What's here

  • Agent client + parsers (Driver.MTConnect) — /probe, /current, and a
    multipart/x-mixed-replace /sample long-poll pump, hand-rolled over System.Xml.Linq.
    Namespace-agnostic LocalName matching, fail-loud InvalidDataException, ring-buffer
    sequence-gap detection with re-baseline, heartbeat watchdog.
  • Type inference (Driver.MTConnect.Contracts) — one pure MTConnectDataTypeInference.Infer
    shared by discovery and runtime, pinned by a golden table test.
  • Observation index — thread-safe, UNAVAILABLEBadNoCommunication, CONDITION worst-of
    (Fault > Warning > Normal > UNAVAILABLE).
  • AdminUI — typed tag-config editor + driver form, registered in TagConfigEditorMap,
    TagConfigValidator, RawDriverTypeDialog and DriverConfigModal.
  • Fixtures + tests — canned 1.3 XML fixtures and a mtconnect/agent:2.7.0.12 + SHDR-adapter
    docker fixture, with an env-gated integration suite.

Testing

Suite Result
MTConnect unit 491 / 491
Integration vs. a real Agent 12 / 12
AdminUI 800 / 800
Core.Abstractions (incl. StatusCodeParityTests, DriverTypeNamesGuardTests) 256 / 256
Full solution build 0 errors

StatusCodeParityTests (new on master) reports 9 MTConnect constants in scope, all matching the
pinned SDK.

Live gate — all 5 legs passed

Run on an isolated stack (otopcua-host:mtconnect, project otopcua-mtc, ports
9220/4860/14340) so the shared otopcua-dev rig and three sibling driver worktrees sharing
otopcua-host:dev were untouched. Fixture at 10.100.0.35:5000.

Driver creatable in /raw · typed config modal renders · config persists and round-trips ·
browse picker commits fullName · deploy → OPC UA read + subscribe .

Read/subscribe verified over opc.tcp://localhost:4860 across all three type paths — Float64
SAMPLE (sinusoid), Int64 EVENT (monotonic), String EVENT (READY → INTERRUPTED) — all Good,
streaming live from the /sample pump.

Worth noting: the live fixture answers in the MTConnect 2.0 namespace while the canned unit
fixtures are 1.3. The namespace-agnostic parsing is what makes both work — now demonstrated
rather than argued.

Defects the gate caught that tests did not

Several of these would have shipped green. Recording them because the class recurs:

  1. RawTags ignored — the driver keyed its index by dataItemId while the runtime routes by
    RawPath, and MTConnectDriverConfigDto had no RawTags member so System.Text.Json silently
    dropped the injected array. Every tag read BadNodeIdUnknown; no value could ever reach a
    client in production.
  2. Registered but unauthorable — factory wired and the guard test green, yet the AdminUI could
    not create the driver: RawDriverTypeDialog's hardcoded type list omitted it and
    DriverConfigModal had no case. Identical to the gap the SQL-poll driver hit, so this is now a
    confirmed repeat pattern rather than a one-off; RawDriverTypeDialogCoverageTests guards it.
    The switch in DriverConfigModal.razor compiles into BuildRenderTree and is unreachable by
    reflection — this mutation survived all 800 AdminUI tests.
  3. Silent /sample stream end — three normal-return paths while the interface promised "run
    until cancelled"; a non-multipart response yielded one document and stopped. Now typed exceptions.
  4. Silent-Healthy subscription — a latched "stream unsupported" flag left the driver reporting
    Healthy with a permanently silent subscription and no log.
  5. PascalCase vs UPPER_SNAKE — numeric EVENT inference matched PartCount case-insensitively,
    but /probe declares PART_COUNT; underscores defeat case-insensitivity, so PART_COUNT typed
    as String. Fixed with a separator-insensitive comparer.

Out of scope — pre-existing, verified against current master, NOT fixed here

  • Config edits silently discarded on Modbus/FOCAS/OpcUaClient (deployment still seals green).
    MTConnect is not affected — verified live.
  • Driver health published after teardown, leaving a stale-Healthy window.
  • IRediscoverable / IHostConnectivityProbe events have no consumer anywhere in src/.
    CLAUDE.md's Change Detection section claims DriverHost consumes the signal; it does not.
  • No driver's Bad/Uncertain sub-code reaches an OPC UA client.
    DriverInstanceActor.QualityFromStatus collapses the status onto a 3-state OpcUaQuality
    (statusCode >> 30) and OtOpcUaNodeManager.StatusFromQuality re-expands Bad to
    StatusCodes.Bad. Deliberate per the enum's own doc comment, but the client-visible consequence
    looks undocumented: #497's 16 corrected constants and the parity guard keep constants internally
    right, while a client still cannot tell BadNoCommunication from BadTypeMismatch. Found via a
    tag reading 0x80000000 that carried the agent's exact source timestamp — proving the publish
    landed and only the status differed.

Notes for review

  • Rebased onto master 123ddc3f. All conflicts were one shape — this driver and the newly-merged
    SQL-poll driver each appending to the same list — resolved by keeping both in eight files.
  • The TrakHound MTConnect.NET dependency was evaluated and removed: the pinned packages carry no
    XML formatter and the streaming client exposes no injectable handler (verified by reflection and
    live invocation). Client and parsers are hand-rolled; Directory.Packages.props is unchanged.
Adds a read-only **MTConnect Agent** driver — the first of the seven curated next-drivers (`docs/plans/2026-07-24-driver-expansion-tracking.md`). Executes `docs/plans/2026-07-24-mtconnect-driver.md` end to end: all 23 tasks, plus a full 5-leg live gate against a **real** MTConnect Agent. Equipment-kind, no COM gateway. Capabilities: `IReadable`, `ISubscribable`, `ITagDiscovery`, `IHostConnectivityProbe`, `IRediscoverable`. Deliberately **not** `IWritable` — MTConnect write-back is a separate protocol surface, deferred with a note in `docs/drivers/MTConnect.md`. ## What's here - **Agent client + parsers** (`Driver.MTConnect`) — `/probe`, `/current`, and a `multipart/x-mixed-replace` `/sample` long-poll pump, hand-rolled over `System.Xml.Linq`. Namespace-agnostic `LocalName` matching, fail-loud `InvalidDataException`, ring-buffer sequence-gap detection with re-baseline, heartbeat watchdog. - **Type inference** (`Driver.MTConnect.Contracts`) — one pure `MTConnectDataTypeInference.Infer` shared by discovery and runtime, pinned by a golden table test. - **Observation index** — thread-safe, `UNAVAILABLE` → `BadNoCommunication`, CONDITION worst-of (Fault > Warning > Normal > UNAVAILABLE). - **AdminUI** — typed tag-config editor + driver form, registered in `TagConfigEditorMap`, `TagConfigValidator`, `RawDriverTypeDialog` and `DriverConfigModal`. - **Fixtures + tests** — canned 1.3 XML fixtures and a `mtconnect/agent:2.7.0.12` + SHDR-adapter docker fixture, with an env-gated integration suite. ## Testing | Suite | Result | |---|---| | MTConnect unit | **491 / 491** | | Integration vs. a **real** Agent | **12 / 12** | | AdminUI | **800 / 800** | | Core.Abstractions (incl. `StatusCodeParityTests`, `DriverTypeNamesGuardTests`) | **256 / 256** | | Full solution build | **0 errors** | `StatusCodeParityTests` (new on master) reports 9 MTConnect constants in scope, all matching the pinned SDK. ## Live gate — all 5 legs passed Run on an **isolated** stack (`otopcua-host:mtconnect`, project `otopcua-mtc`, ports 9220/4860/14340) so the shared `otopcua-dev` rig and three sibling driver worktrees sharing `otopcua-host:dev` were untouched. Fixture at `10.100.0.35:5000`. Driver creatable in `/raw` ✅ · typed config modal renders ✅ · config persists and round-trips ✅ · browse picker commits `fullName` ✅ · **deploy → OPC UA read + subscribe ✅**. Read/subscribe verified over `opc.tcp://localhost:4860` across all three type paths — Float64 SAMPLE (sinusoid), Int64 EVENT (monotonic), String EVENT (`READY → INTERRUPTED`) — all Good, streaming live from the `/sample` pump. Worth noting: the live fixture answers in the MTConnect **2.0** namespace while the canned unit fixtures are **1.3**. The namespace-agnostic parsing is what makes both work — now demonstrated rather than argued. ## Defects the gate caught that tests did not Several of these would have shipped green. Recording them because the *class* recurs: 1. **`RawTags` ignored** — the driver keyed its index by `dataItemId` while the runtime routes by `RawPath`, and `MTConnectDriverConfigDto` had no `RawTags` member so `System.Text.Json` silently dropped the injected array. Every tag read `BadNodeIdUnknown`; **no value could ever reach a client in production.** 2. **Registered but unauthorable** — factory wired and the guard test green, yet the AdminUI could not create the driver: `RawDriverTypeDialog`'s hardcoded type list omitted it and `DriverConfigModal` had no `case`. Identical to the gap the SQL-poll driver hit, so this is now a confirmed repeat pattern rather than a one-off; `RawDriverTypeDialogCoverageTests` guards it. The `switch` in `DriverConfigModal.razor` compiles into `BuildRenderTree` and is unreachable by reflection — this mutation survived all 800 AdminUI tests. 3. **Silent `/sample` stream end** — three normal-return paths while the interface promised "run until cancelled"; a non-multipart response yielded one document and stopped. Now typed exceptions. 4. **Silent-Healthy subscription** — a latched "stream unsupported" flag left the driver reporting **Healthy** with a permanently silent subscription and no log. 5. **PascalCase vs UPPER_SNAKE** — numeric EVENT inference matched `PartCount` case-insensitively, but `/probe` declares `PART_COUNT`; underscores defeat case-insensitivity, so `PART_COUNT` typed as String. Fixed with a separator-insensitive comparer. ## Out of scope — pre-existing, verified against current master, NOT fixed here - Config edits silently discarded on Modbus/FOCAS/OpcUaClient (deployment still seals green). MTConnect is **not** affected — verified live. - Driver health published *after* teardown, leaving a stale-Healthy window. - `IRediscoverable` / `IHostConnectivityProbe` events have **no consumer** anywhere in `src/`. CLAUDE.md's Change Detection section claims `DriverHost` consumes the signal; it does not. - **No driver's `Bad`/`Uncertain` sub-code reaches an OPC UA client.** `DriverInstanceActor.QualityFromStatus` collapses the status onto a 3-state `OpcUaQuality` (`statusCode >> 30`) and `OtOpcUaNodeManager.StatusFromQuality` re-expands `Bad` to `StatusCodes.Bad`. Deliberate per the enum's own doc comment, but the client-visible consequence looks undocumented: #497's 16 corrected constants and the parity guard keep constants internally right, while a client still cannot tell `BadNoCommunication` from `BadTypeMismatch`. Found via a tag reading `0x80000000` that carried the agent's *exact* source timestamp — proving the publish landed and only the status differed. ## Notes for review - Rebased onto master `123ddc3f`. All conflicts were one shape — this driver and the newly-merged SQL-poll driver each appending to the same list — resolved by keeping **both** in eight files. - The TrakHound MTConnect.NET dependency was evaluated and **removed**: the pinned packages carry no XML formatter and the streaming client exposes no injectable handler (verified by reflection and live invocation). Client and parsers are hand-rolled; `Directory.Packages.props` is unchanged.
Author
Owner

The four pre-existing findings listed under Out of scope are now tracked:

  • #516 — driver config edits silently discarded on Modbus/FOCAS/OpcUaClient (deployment still seals green). MTConnect is not affected; verified live on this branch's gate.
  • #517 — driver health published after teardown, leaving a stale-Healthy window.
  • #518IRediscoverable / IHostConnectivityProbe events have no consumer in src/; CLAUDE.md's Change Detection section is wrong.
  • #519 — no driver's Bad/Uncertain status sub-code reaches an OPC UA client (3-state OpcUaQuality collapse).

None of them block this PR — all four are pre-existing on master and were verified there, not merely inherited.

The four pre-existing findings listed under **Out of scope** are now tracked: - #516 — driver config edits silently discarded on Modbus/FOCAS/OpcUaClient (deployment still seals green). MTConnect is **not** affected; verified live on this branch's gate. - #517 — driver health published after teardown, leaving a stale-Healthy window. - #518 — `IRediscoverable` / `IHostConnectivityProbe` events have no consumer in `src/`; CLAUDE.md's Change Detection section is wrong. - #519 — no driver's Bad/Uncertain status sub-code reaches an OPC UA client (3-state `OpcUaQuality` collapse). None of them block this PR — all four are pre-existing on `master` and were verified there, not merely inherited.
dohertj2 added 34 commits 2026-07-27 14:02:17 -04:00
Adds the /current and /sample legs to MTConnectAgentClient:

- MTConnectStreamsParser: hand-rolled System.Xml.Linq parse of an
  MTConnectStreams document into MTConnectStreamsResult. Observations are
  every element child of <Samples>/<Events>/<Condition>, keyed by
  dataItemId (the element NAME is the data item's type in PascalCase, so
  a fixed name set would drop observations). A CONDITION's value is its
  element name, not its text - <Normal/> is empty - and <Unavailable/>
  normalizes onto the same UNAVAILABLE sentinel a Sample/Event carries as
  text, so Task 8's no-comms mapping sees one token. Timestamps are
  normalized to DateTimeKind.Utc explicitly.
- IsSequenceGap(requestedFrom, chunk) => chunk.FirstSequence >
  requestedFrom, so Task 11's pump can re-baseline after a ring-buffer
  overflow. Equality is NOT a gap.
- SampleAsync: ResponseHeadersRead + a hand-rolled
  multipart/x-mixed-replace frame reader (Content-length fast path,
  boundary-scan fallback), bounded by a heartbeat watchdog derived from
  HeartbeatMs so a silent Agent faults instead of wedging the pump - the
  S7 frozen-peer shape (arch-review R2-01). The long poll gets its own
  HttpClient with an infinite Timeout so the unary /probe + /current
  deadline stays bounded.

Task 0 package decision, option (c): both TrakHound PackageReferences and
their PackageVersions are dropped. MTConnectHttpClientStream takes a URL
and dials its own socket (no handler/stream seam, so it cannot serve a
socket-free unit suite), and it emits already-parsed documents through the
formatter lookup Task 6 proved is missing - framing-only reuse was never
actually on offer. The driver now depends on nothing but the BCL. Recorded
in the plan's Task 0 CORRECTION block.

Also folds in two Task 6 review carry-overs: the stale
IMTConnectAgentClient doc comment claiming a TrakHound-backed
implementation, and a probe test constructing a mixed-namespace vendor
extension (<x:Pump> with default-namespace <DataItems> children) that
backs the parser's ignore-the-namespace claim with a test.

187/187 green.
Code review of c46540ae approved the framing algorithm but moved the risk
onto the contract around it.

C1 (critical). SampleAsync returned normally on three different events:
EOF, the closing --boundary--, and a response that was not multipart at
all (where it yielded one parsed snapshot and finished). The seam
documents the stream as yielding until ct is cancelled, so a Task 11 pump
written to that contract would silently drop its subscription or hot-loop
reconnecting; the non-multipart leg reported a configuration error as a
healthy finished stream, which is the #485 quiet-successful-termination
shape aimed at the very next task. Every non-cancellation end now throws:
MTConnectStreamEndedException (ConnectionClosed / ClosingBoundary -
transient) or MTConnectStreamNotSupportedException (configuration -
reconnecting reproduces it forever), sharing one catchable base. The
non-multipart body is still parsed first so an Agent's own MTConnectError
text wins, but the document is NOT yielded.

I1. IsSequenceGap moved to IMTConnectAgentClient (static) and its first
parameter is now expectedFrom. The old name and doc were wrong for every
chunk after the first - the correct comparand is the PREVIOUS chunk's
NextSequence, and comparing against the opening "from" argument reports a
gap on every chunk once the ring buffer rolls, i.e. an endless /current
re-baseline storm. Both doc blocks also now record that cppagent answers
from < firstSequence with an OUT_OF_RANGE MTConnectError under HTTP 200,
which surfaces as InvalidDataException and NOT as a gap - so Task 11 must
treat that parse failure as a re-baseline trigger too.

I2. Every multipart test served the whole body from one buffer, so every
framing test completed in a single ReadAsync - the split-boundary path,
the split-header path and the multi-fill loop were correct by inspection
only. A ChunkedStream double (N bytes per read, N = 1/3/7) now drives the
fixtures through a split transport, plus a >16 KB document that forces a
buffer resize. Falsifiability: removing either scan overlap, or
collapsing the fill loop, fails ONLY the new chunked tests.

I3. Disposal mid-enumeration surfaces as OperationCanceledException via
an internal dispose-linked token, not a raw ObjectDisposedException that
Task 9's re-init would inflict on an enumerating pump.

I5. HeartbeatMs, SampleIntervalMs and SampleCount join RequestTimeoutMs
in construction-time positive-value validation. All three reach the query
string and an Agent answers heartbeat=0 with an HTTP-200 MTConnectError
that names no config key.

I4/M2. The no-Content-length framing fallback logs a one-shot warning
(the client takes an optional ILogger); a multipart response with no
boundary parameter fails fast instead of degrading into a watchdog
timeout.

M5/M6. Shared element/attribute reading rules extracted to MTConnectXml;
the probe parser documents why it alone does not trim BOM/whitespace. The
literal U+FEFF in source became a '' escape.

Also, from Task 8: MTConnectObservation gained IsStructured (default
false), set from element.HasElements. A DATA_SET/TABLE observation's
<Entry> children concatenate through element.Value to nonsense ("12" for
two entries) that the index would publish as Good, and only the parser
can tell that apart from a legitimate space-bearing Message. False for
CONDITION observations - their value comes from the element name, so
child content cannot corrupt it.

275/275 green in this suite's own files.
The concurrency test asserted a post-Apply post-condition from inside the
race window: dev1_pos is authored, so a reader beating the first Apply
correctly observes BadWaitingForInitialData, which the test's two-member
"legal" set omitted. Consistently red (10/10) rather than intermittent.

Rewritten to assert only properties that hold at every instant — the whole
(status, value, source timestamp) triple against the three legal snapshots,
which is the real torn-snapshot check — plus a read counter guarding a
vacuous pass and one deterministic closing Apply for an exact end state.
The index is unchanged here; BadWaitingForInitialData is a designed state.

Also codes structured (DATA_SET / TABLE) observations BadNotSupported now
that the parser supplies MTConnectObservation.IsStructured, so a two-entry
data set no longer surfaces as the Good string "12".
MTConnectDriver implements IDriver only: connection-free ctor, initialize
(deadline-bounded /probe + /current, caching the device model, the agent
instanceId, and a primed observation index), reinitialize, shutdown, health,
footprint, and cache flush.

Decisions worth knowing:

- The driverConfigJson argument is HONOURED, not ignored. DriverInstanceActor
  delivers a config change only via ReinitializeAsync(json) on the live
  instance, so a driver reading only its ctor options would turn every MTConnect
  config edit into a silent no-op that still sealed the deployment green.
  ParseOptions lives on the driver; Task 15's factory must delegate to it rather
  than deserialize a second DTO.
- /probe ok but priming /current failing is Faulted, not Healthy-with-no-data:
  the index IS the read surface and the /sample cursor comes from /current.
- ReinitializeAsync rebuilds the client whenever ANY option the client reads at
  construction changed - AgentUri, DeviceName, RequestTimeoutMs, HeartbeatMs,
  SampleIntervalMs, SampleCount - not just the first two. The timing knobs are
  baked into the deadlines, the watchdog window, and the /sample query string.
- An unparseable config faults a cold start but leaves a RUNNING driver serving
  its previous valid configuration (the deployment fails instead).
- IMTConnectAgentClient now extends IDisposable rather than the driver doing
  `as IDisposable`, which would silently no-op against a non-disposable fake and
  leak an HttpClient + socket handler per re-deploy. Sync, not async: every
  resource behind the seam is sync-disposable, and the async unwind belongs to
  the SampleAsync enumerator the pump owns.
- Flush drops the probe/browse cache and keeps the index; every model consumer
  goes through GetOrFetchProbeModelAsync so a flush cannot wedge browse.

Tests: CannedAgentClient (shared, deterministic - channel-backed scripted
/sample with no timers, call counts, disposal tracking, failure injection) +
27 lifecycle tests. 308/308 in the project.
One deadline-bounded /current per batch, answered out of that one whole-device
document: N references cost one round-trip, one snapshot each, in request order,
duplicates included.

DEVIATION (deliberate, from the plan's implied shared-index write): the response
is indexed into a PER-CALL snapshot index, never into the driver's shared
observation index. That index is written by Task 11's /sample pump and is
last-write-wins with no timestamp arbitration; a read folding its /current into
it would be a second writer racing the first, and /current is frequently the
OLDER document (the Agent composes it while the pump's newer delta is in
flight). Losing that race rolls a subscribed value backwards and leaves it there
until the data item next changes. Both paths coerce through the same
MTConnectObservationIndex logic, so a read and a subscription report a given
observation identically -- the read path is simply a pure function of
(document, authored tags).

Failure posture is the inverse of InitializeAsync: nothing but genuine caller
cancellation crosses the capability boundary. Unreachable Agent / blown deadline
/ unusable answer => every ref codes BadCommunicationError and the driver
degrades (never downgrading Faulted); no client at all (pre-initialize, faulted,
post-shutdown) => BadNotConnected with health untouched. The index's
BadWaitingForInitialData / BadNodeIdUnknown / BadNoCommunication / BadNotSupported
distinctions pass through unmodified.

21 tests pinning arity, order, duplicates, empty batch, one-round-trip, each Bad
code, read-time freshness, the anti-clobber invariant, the deadline, and
cancellation-propagates-but-agent-failure-does-not. CannedAgentClient gains a
cancellation-observing CurrentGate (still no timers or sleeps of its own).
Test csproj takes the AbCip/S7 OTOPCUA0001 NoWarn -- this suite calls the
capability directly by design.

329/329 green.
Important 1 - the probe-model triple was read outside _lifecycle while every
write happened under it. Packed (Client, ProbeModel, ProbeModelDataItemCount)
into one immutable AgentSession swapped by a single Volatile.Write, matching
what _index already does, rather than locking the readers: both await the
network, so taking _lifecycle would stall a shutdown for a whole
RequestTimeoutMs and would widen the non-reentrancy hazard. GetOrFetch and
Flush re-publish via CompareExchange so a late re-cache cannot undo a
concurrent teardown/re-init, and a client disposed mid-fetch now surfaces as
the same "not connected" InvalidOperationException browse already handles
instead of a raw ObjectDisposedException.

Important 2 - HasConfigBody decided emptiness by matching the literals "{}" /
"[]", so "{ }", "{\n}" and every pretty-printed empty document fell through to
ParseOptions, failed the required-AgentUri check, and turned a semantically
empty config into a cold-start fault. Now parsed: an object/array with no
elements (or a bare null) is empty; malformed text is deliberately NOT empty so
ParseOptions produces the real quoted error rather than silently starting on
stale options.

Important 3 - documented the _lifecycle non-reentrancy hazard in the code, on
both the semaphore and StopSampleStreamAsync, naming Task 11's re-baseline as
the specific path that would deadlock and giving the CurrentAsync-directly
pattern that avoids it.

Important 4 - removed the Initialize/Reinitialize asymmetry rather than
documenting it. Both now share one rule via ResolveIncomingOptions: an
unreadable config document never destroys working state, and faults only a
driver that had none. InitializeAsync previously tore down before parsing, so a
bad document on a live instance destroyed a healthy client - the exact outcome
ReinitializeAsync was written to avoid.

Minors: SafeDispose traces the swallowed disposal fault at Debug (a client that
cannot be released is how a handle leak starts); the RequirePositive test is a
Theory over all four timing knobs, not just RequestTimeoutMs (arch-review
01/S-6); the footprint test no longer overclaims "is zero before initialize".

CannedAgentClient gains a one-shot ProbeGate so a lifecycle change landing
mid-request is deterministic - no timers. 346/346 (329 + 17). Six mutations
verified: fetch-CAS, disposed-translation, flush retired-session guard,
literal HasConfigBody, teardown-before-parse, and two dropped RequirePositive
calls each fail only their own tests.
One shared /sample long poll behind every subscription handle. Subscribe fires
initial data per reference from the primed /current (Part 4 convention) and
returns without waiting on the stream; the pump runs on its own task under its
own token — never the caller's Subscribe token, which is disposed the moment
that call returns.

The pump owns every way the sequence can break:

- sequence gap, measured against the RUNNING cursor (the previous chunk's
  nextSequence). Comparing against the opening `from` reports a gap on every
  chunk once the buffer rolls — a /current re-baseline storm.
- OUT_OF_RANGE under HTTP 200 (InvalidDataException out of SampleAsync), which
  IsSequenceGap cannot see at all — without it a driver recovers from falling a
  little behind but not from falling a lot.
- agent restart, checked BEFORE the gap because a restart resets sequences and
  so usually trips the gap check too; it clears the index (the held values
  describe a device model that no longer exists) and tells the subscribers.
- every chunk advances the cursor, heartbeats included.

Re-baseline calls CurrentAsync directly on the client the pump already holds:
routing it through ReinitializeAsync would take the non-reentrant lifecycle
semaphore from inside a pump a lifecycle method may already be awaiting, and
hang the driver with no exception and no log. StopSampleStreamAsync is filled
in (same call sites) and InitializeAsync now stops the stream before teardown
too, so a re-Initialize on a live instance cannot leave a pump enumerating a
disposed client.

MTConnectStreamEnded/TimeoutException reconnect under a geometric backoff with
a 100 ms growth floor (MinBackoffMs defaults to 0, and 0 x multiplier is still
0). MTConnectStreamNotSupportedException does NOT retry — it latches, reports
loudly, and is cleared only by a re-initialize.

Health precedence is explicit: /current and /sample fail independently, so each
path owns a flag, clears only its own, and Healthy requires both clear. Neither
can paper over the other's failure.

29 new tests, all deterministic — no sleeps, no wall-clock assertions. The fake
grew per-generation sample streams (so a reconnect has somewhere to land),
scripted /current answers, scripted sample failures, and a chunk-consumed
signal that also fires when the consumer abandons the stream. 375/375 green.
C1 (critical): a latched "this endpoint cannot stream" verdict could end with a
GREEN driver holding a permanently silent subscription. DriverInstanceActor
handles a tag-set change as Unsubscribe-then-Subscribe with no re-initialize;
the unsubscribe cleared the stream-degraded flag, the resubscribe was refused by
the latch without a word, and one successful read then reported Healthy.
StartSampleStreamCore now re-asserts the degradation and logs a Warning naming
the remedy, and teardown no longer clears the flag while the latch is set.

NOT promoted to Faulted: DriverHealthReport maps any Faulted driver to a /readyz
503, so that would de-ready the whole node over one misconfigured Agent whose
reads are perfectly healthy. Faulted stays for the case that earns it.

I1: teardown waits are bounded (5 s) and honour the caller's token. They were
unbounded and ignored it, so DriverInstanceActor's 5 s budget was inert and
PostStop — which blocks a dispatcher thread on ShutdownAsync while holding the
lifecycle semaphore — could be wedged forever by one blocking subscriber. The
cancellation source is disposed only when the loop is provably gone. Applied to
StopProbeLoopAsync too: Task 13 reproduced the identical shape, and closing the
class in one method while leaving the other as the pattern to copy is worse than
not closing it.

I2: the reconnect ladder was monotonic for the process lifetime, so ~9 unrelated
drops pinned the driver at MaxBackoffMs forever. A stream that delivered before
dropping now starts a fresh ladder (at attempt 1, not 0, so MinBackoffMs is
still honoured).

I3: MaxBackoffMs <= 0 clamped every delay to zero — an operator-authorable
reconnect spin. Treated as unset, like a multiplier that cannot grow.

I4: the session published instanceId without NextSequence, so after a restart it
held the new agent's id beside the dead one's cursor, and a gap/OUT_OF_RANGE
re-baseline (id unchanged) never published the cursor at all. Both move in one
CAS, and the pump publishes its cursor as it exits.

I5: OnDataChange was a multicast Invoke — the first throwing handler aborted the
rest of the list, starving every later subscriber. Now walked by hand with the
catch inside the loop. The test that claimed to cover this registered the
recorder BEFORE the thrower, so it passed regardless; swapped, it was red.
Faults are latched to one Warning per stream generation (Debug thereafter) so a
consistently-throwing consumer cannot flood the log.

Also: the pump restarts after an unexpected fault (IsCompleted, not null); a
device-scope that matches nothing is a Warning, not a Debug tally; a device or
component with neither name nor id is skipped rather than emitting a blank path
segment; DiscoverAsync's remark no longer claims DriverInstanceActor retries
(it does not for a Once driver, and injection is dormant in v3); and two flake
seeds in the fake are gone (Dispose re-read its own counter; _disposeCts was
disposed under a racing SampleAsync).

439/439. Every changed behaviour falsified by mutation.
The factory carries NO config DTO of its own: CreateInstance delegates to
MTConnectDriver.ParseOptions, the single authority for the config document.
A second DTO would drift from the parse the runtime's ReinitializeAsync path
uses, and the drift would only surface at deploy time.

Construction is connection-free (agentClientFactory: null) because the Wave-0
universal browser builds a throwaway instance per browse probe, and the
returned instance is never narrowed — its five capability interfaces ARE the
runtime's dispatch surface. Pinned by tests asserting all five plus the
deliberate absence of IWritable.

DriverTypeName is the literal "MTConnect"; Task 16 adds DriverTypeNames.MTConnect
and the host registration that must equal it.
Register the MTConnect factory + probe with the Host, add the
DriverTypeNames.MTConnect constant, and keep DriverTypeNamesGuardTests green.

- DriverTypeNames: new MTConnect const + appended to All.
- DriverFactoryBootstrap: MTConnectDriverFactoryExtensions.Register in
  Register(...) at the default Tier A (managed HttpClient/XML, in-process;
  Tier C is the only tier arming process-recycle, wrong here), and
  TryAddEnumerable(IDriverProbe -> MTConnectDriverProbe) in
  AddOtOpcUaDriverProbes so the probe reaches admin-only nodes (the
  admin-pinned Test-Connect singleton) without double-registering on a
  fused admin,driver node.
- Host.csproj: ProjectReference to Driver.MTConnect (required to compile
  the Register call).
- Core.Abstractions.Tests.csproj: ProjectReference to Driver.MTConnect so
  the guard's bin scan discovers the factory. This and the constant MUST
  land together -- verified RED (2/4 facts) with the constant alone.
- DriverProbeRegistrationTests: MTConnect added to AdminUiDriverTypeKeys;
  its idempotency fact asserts distinct-probe-count and goes RED without
  this (and RED if TryAddEnumerable is downgraded to AddSingleton).

Reconciles all four "MTConnect" literals onto the one constant: the
factory's DriverTypeName, MTConnectDriver.DriverType, and
MTConnectDriverProbe.DriverType now all alias DriverTypeNames.MTConnect
(no circular reference -- Core.Abstractions is a leaf both driver
projects already reference). This is the repo's TwinCat/Focas anti-drift
convention.
Two review findings on Task 14's MTConnectDriverProbe, both red-first:

- CancelAfter(effectiveTimeout) sat before the try block with only a low-end
  floor on a non-positive timeout, never a high-end cap. A pathological
  timeout (e.g. TimeSpan.FromDays(1000)) threw an uncaught
  ArgumentOutOfRangeException straight out of CancelAfter's ~49.7-day legal
  range, violating the probe's own "Never throws" contract. Not reachable
  through today's only caller (AdminOperationsActor clamps to [1,60]s and
  wraps the call), but a landmine for any future caller without that clamp.
  Fixed by clamping effectiveTimeout to a new MaxTimeout (10 minutes).

- The final `catch (Exception ex) { return new(false, ex.Message, null); }`
  forwarded ex.Message verbatim for any exception type not enumerated above
  it, breaking the redaction discipline every other catch was audited for
  (AgentUri may carry userinfo credentials). Not exploitable by any
  currently-reachable exception type, but an open door for a future one.
  Fixed to build a message from the already-redacted safeUri + the
  exception's type name instead of its message.

Also: a genuine non-2xx stub-handler test (prior HttpRequestException
coverage was connection-refused only), a credentialed-agentUri +
successful-probe redaction test, and a one-line doc remark on the accepted
reachable-vs-deployable gap.
MTConnectTagConfigModel: pure FromJson/ToJson/Validate for the MTConnect
tag TagConfig JSON blob, mirroring ModbusTagConfigModel/OpcUaClientTagConfigModel.
Fields: fullName (DataItem@id, required), dataType (DriverDataType override,
written as an enum name string), mtCategory/mtType/mtSubType/units (probe
metadata), mtDevice/mtComponent (author context). Preserves unknown JSON
keys across load->save (isHistorized/historianTagname and anything else).

Guards against the enum-serialization trap (numeric dataType would fault the
driver at deploy) both on write (always TagConfigJson.Set via enum name) and
on read (Validate() rejects a dataType that was stored as a bare digit
string, since Enum.TryParse silently accepts numeric text).

AdminUI.csproj gains a ProjectReference to Driver.MTConnect.Contracts,
matching the existing POCO-only driver-Contracts pattern used by the other
six typed tag editors.

Scope: pure model only (Task 17). The razor editor shell + TagConfigEditorMap/
TagConfigValidator registration is Task 18.
The driver could not receive data after a real deploy. The runtime hands every
driver its authored tags as a RawTags array (RawPath identity + TagConfig blob,
injected by DriverDeviceConfigMerger) and then subscribes, reads, and routes
published values by RawPath. MTConnectDriverConfigDto declared no RawTags
property, so System.Text.Json silently dropped the array, and every reference
the server passed missed an index keyed by DataItem id: every value came back
BadNodeIdUnknown, with the whole suite green because every test handed the
driver its own Tags array directly.

- MTConnectDriverOptions gains RawTags; the config DTO binds it (verbatim — a
  bad blob is skipped per-tag at binding time, never fails the deployment).
- A new TagBinding, derived from the options and swapped with them in one write,
  carries RawPath -> dataItemId, its one-to-many reverse, and the definition set
  the observation index coerces against. Subscribe/Read resolve through it; the
  fan-out expands each touched dataItemId into every RawPath bound to it and
  publishes under THAT reference — the line the blocker turned on.
- Coercion type precedence: the blob's driverDataType/dataType (both spellings —
  the AdminUI's MTConnectTagConfigModel writes the latter), else a Tags entry for
  the same DataItem, else the Agent's own /probe declaration via
  MTConnectDataTypeInference (what makes a browse-committed {"address": id} blob
  publish as a number), else String. A present-but-invalid type rejects that tag.
- An unmapped reference falls through unchanged, so the dataItemId-keyed CLI
  surface and every existing test keep working, and an unclaimed RawPath reports
  Bad rather than throwing.

15 new tests build their config through the real DriverDeviceConfigMerger; all
four mutations (publish the dataItemId, drop the RawTags binding, drop the
derived coercion type, drop the reverse-map expansion) are caught.
Registers the MTConnect typed tag editor in TagConfigEditorMap /
TagConfigValidator (keyed off DriverTypeNames.MTConnect, never a literal) and
adds the razor shell over Task 17's MTConnectTagConfigModel.

The shell stays trivial: the /probe-sourced mtCategory/mtType/mtSubType/units
row is rendered disabled + readonly with NO binding of any kind, and no
inferred-type hint is shown — MTConnectDataTypeInference.Infer() also keys on
the DataItem `representation`, which the tag-config model does not carry, so
calling it here would agree with the browse picker for ordinary items and
silently disagree for exactly the DATA_SET/TABLE/TIME_SERIES ones.

Also fixes the picker -> editor round trip, which was broken in both
directions:

- RawBrowseCommitMapper.BuildTagConfig had no MTConnect branch, so a committed
  tag landed as the generic {"address": "<dataItemId>"} while the model read
  only `fullName`. The data plane kept working (the driver accepts all three id
  spellings), so the only symptom was an empty DataItem-id field in the editor
  — and saving from that state stamped fullName:"" over the tag.
- MTConnectTagConfigModel.FromJson now accepts dataItemId/address as fallbacks
  (fixing tags committed before this change) and ToJson normalises onto
  `fullName`, dropping the aliases so the two spellings cannot drift.
An MTConnect driver instance could not be authored at all: RawDriverTypeDialog
(the only DriverInstance creation surface) offered a hardcoded 9-entry list
without it, and DriverConfigModal's default: branch renders a warning with no
raw-JSON fallback — so even a hand-inserted row could not be configured and
DriverConfig stayed "{}", on which ParseOptions throws "missing required
AgentUri".

Adds the typed MTConnectDriverForm (the consistent sibling pattern) covering
agentUri / deviceName / the four polling knobs / probe / reconnect, wires the
dispatch case, and offers the type in the dialog.

- All decisions live in the static MTConnectDriverForm.BuildConfigJson +
  MTConnectFormModel (plain C#), because this project has no bUnit.
- The wire shape mirrors the driver's private MTConnectDriverConfigDto, NOT
  MTConnectDriverOptions: the latter's TimeSpan probe knobs would serialise as
  "00:00:05" and never bind to the driver's integer intervalMs.
- arch-review 01/S-6: a non-positive timing knob is REMOVED from the document
  rather than written, so ParseOptions substitutes the driver's own positive
  default instead of the driver faulting at Initialize on RequirePositive.
  Removal (not just skipping) also stops a stale positive value surviving and
  disagreeing with what the form shows.
- Unknown top-level keys survive a load/save, so the driver's hand-authored
  tags[] surface is not silently deleted by opening the form.
- _jsonOpts carries JsonStringEnumConverter, satisfying the
  DriverPageJsonConverterTests fleet guard properly rather than by exemption.

New RawDriverTypeDialogCoverageTests resolves the offered set through
DriverTypeNames.All, so the next registered driver fails here until the dialog
offers it.
The first and only thing in the MTConnect workstream that exercises the driver
against a real Agent; everything else runs on canned XML.

Fixture (Docker/): two services, both stock images with this folder bind-mounted.
- `agent`   mtconnect/agent:2.7.0.12 on :5000. NOTE the repo name: the source
            project is mtconnect/cppagent but the PUBLISHED image is
            mtconnect/agent; mtconnect/cppagent does not exist on Docker Hub.
- `adapter` a stdlib SHDR feeder. Required, not optional: the agent image ships
            only the binary + schemas/styles, so a lone Agent answers /probe and
            then reports every observation UNAVAILABLE forever, which can prove
            nothing about reads or streaming.

Devices.xml seeds one DataItem per inference branch (SAMPLE+units, TIME_SERIES,
PART_COUNT/LINE_NUMBER, controlled vocab, DATA_SET, CONDITION), gives every named
item `name != id` (the inverse of the hand-authored unit fixtures), and leaves one
EVENT permanently unfed so UNAVAILABLE -> BadNoCommunication has a live subject.

Suite (12 tests) asserts STRUCTURALLY against the Agent's own /probe response, never
by literal id, so it survives an edit to Devices.xml and can be pointed at a real
machine tool via MTCONNECT_AGENT_ENDPOINT. It skips cleanly (12/12) when no Agent
answers, and each test carries a hard [Fact(Timeout)] so a half-up fixture cannot
wedge a build.

Three findings from bringing the fixture up, each now pinned in a comment:
- agent.cfg must be pure ASCII; one non-ASCII byte in a COMMENT makes the config
  parser reject the whole file with a bare "Failed / Stopped at line: N" and exit.
- `sampleCount` is an attribute of a TIME_SERIES observation, not of a DataItem
  declaration. A real Agent meeting one on a declaration DROPS THE ENTIRE DATA ITEM
  from the device model, so the inference only ever sees null and a live TIME_SERIES
  tag is always variable-length. Asserted, not ignored.
- The Agent's own <Agent> self-model publishes update-rate SAMPLEs that tick whether
  or not any adapter is attached. Excluding them is load-bearing: with them included
  the "live stream delivered a changed value" test passed with the fixture's data
  source deliberately stopped.

MTConnectError-under-HTTP-200 is NOT covered live and cannot be: cppagent 2.7 answers
an unknown device 404 and an out-of-range sequence 400, each with a well-formed error
body. That shape stays canned-only, and the suite says so.
- docs/drivers/MTConnect.md: getting-started guide for the P1 Agent MVP —
  config keys read off MTConnectDriverOptions/ConfigDto, capability surface,
  RawPath->dataItemId coercion precedence, UNAVAILABLE->BadNoCommunication +
  the rest of the quality-code table, CONDITION-as-String, browse-via-the-
  universal-browser, the fixture recipe (links the existing IntegrationTests
  Docker README instead of duplicating it), and a Known limitations section
  covering the two pre-existing fleet-wide gaps this build surfaced
  (IRediscoverable/IHostConnectivityProbe have no server consumer; no driver
  form blocks Save on validation). Records write-back (MTConnect Interfaces),
  P1.5 (native alarms, TIME_SERIES arrays, EVENT->enum), and P2 (SHDR ingest)
  as deferred per design doc SS3.6/SS9. Documents where the build diverged
  from the design: TrakHound MTConnect.NET was dropped entirely (no XML
  formatter in the pinned packages, no injectable HTTP handler) in favor of
  a hand-rolled System.Xml.Linq client, namespace-agnostic on LocalName.
- docs/drivers/README.md: adds MTConnect to the ground-truth driver table,
  the per-driver doc list, and the fixture coverage-map list.
- docs/plans/2026-07-24-driver-expansion-tracking.md: marks the MTConnect
  Wave-2 row Done (22/23 tasks; Task 21 live gate tracked separately in the
  plan file, not touched here), corrects mtconnect/cppagent -> mtconnect/agent
  in the fixture note, and links the new driver guide.

Deferred-cleanup decision (Task 1 review follow-up): removed
GenerateDocumentationFile/NoWarn CS1591 from Driver.MTConnect.Contracts's
csproj to match all eight sibling .Contracts projects, none of which carry
it. Verified both the Contracts project alone and the full solution still
build clean (0 warnings, 0 errors) with the flags gone — the existing XML
doc comments don't depend on GenerateDocumentationFile to compile.
test(mtconnect): close live-gate leg 5 — deploy -> OPC UA read/subscribe PASSED
v2-ci / build (pull_request) Successful in 6m48s
v2-ci / unit-tests (pull_request) Failing after 18m6s
813e445936
Re-ran the gate on the rebased branch against a freshly rebuilt
otopcua-host:mtconnect image, so it exercises the merged code.

The 2026-07-24 blocker (antiforgery cookie collision between the running
otopcua-dev rig on :9200 and the isolated stack on :9220) is sidestepped
rather than worked around: the headless deploy API
(POST /api/deployments + X-Api-Key) is AllowAnonymous().DisableAntiforgery()
by design, so cookie scoping is structurally irrelevant to it. No browser
needed — the recommended recipe for any future isolated-stack gate.

Both deploys sealed (DeploymentStatus.Sealed, FailureReason NULL) with both
MAIN nodes acking. Read + subscribe verified over opc.tcp://localhost:4860
across all three type paths: Float64 SAMPLE (sinusoid), Int64 EVENT
(monotonic), String EVENT (READY -> INTERRUPTED). This closes the last
unproven link — driver seam was already covered by the live integration
suite; leg 5 adds DeploymentArtifact -> address space -> OPC UA publish.

Two findings recorded in the plan:

- A bad authored dataType degrades to exactly ONE skipped tag, loudly
  (per-tag warning naming the expected keys, BadNodeIdUnknown, "every other
  tag is unaffected") while the rest keep streaming — the intended
  fail-isolated behaviour, demonstrated rather than argued. Correcting it
  took effect with no restart, showing MTConnect is not subject to the
  separately-tracked config-edits-discarded defect.

- fixture_asset_changed reading 0x80000000 is NOT an MTConnect defect. The
  driver maps the agent's UNAVAILABLE to BadNoCommunication correctly; the
  shared publish path collapses every status to a 3-state OpcUaQuality enum
  (DriverInstanceActor.QualityFromStatus, statusCode >> 30) and re-expands
  Bad to StatusCodes.Bad (OtOpcUaNodeManager.StatusFromQuality). Deliberate
  per the enum's own doc comment, but the client-visible consequence appears
  undocumented: no driver's Bad/Uncertain sub-code ever reaches a client.
  Tracked separately; out of scope here.

Also records the rebase onto master 123ddc3f and confirms StatusCodeParityTests
now covers 9 MTConnect constants, all passing.
dohertj2 force-pushed feat/mtconnect-driver from 7a48a6637b to 813e445936 2026-07-27 14:02:17 -04:00 Compare
dohertj2 merged commit 90bdaa4437 into master 2026-07-27 14:02:29 -04:00
Sign in to join this conversation.