24 KiB
Worker IPC / STA / Conversion Review (2026-12-02)
Scope: src/ZB.MOM.WW.MxGateway.Worker/{Ipc,Sta,Conversion,Bootstrap}/, Program.cs, WorkerApplication.cs at HEAD 54367e74. Other code was read only to confirm a finding. Read-only review; nothing was built or run.
Paths below are relative to src/ZB.MOM.WW.MxGateway.Worker/.
Summary
| ID | Severity | Category | Confidence | Title |
|---|---|---|---|---|
| WIP-001 | High | Bug | Plausible (mechanism confirmed) | Unbounded message-pump drain starves STA commands and the activity stamp, so sustained event load is reported as StaHung |
| WIP-002 | High | Performance | Confirmed | None of the perf.md worker fixes are on main; the per-event thread-pool path is unchanged |
| WIP-003 | Medium | Bug | Plausible | Time-typed array and FILETIME conversion throws on unexpected element shapes, and one throw faults the whole session |
| WIP-004 | Medium | Bug | Confirmed (trigger unlikely) | Integer array conversion narrows uint/object[] elements to int and overflows where the scalar path widens |
| WIP-005 | Medium | Bug | Confirmed | Worker-side validation exceptions are returned as MxaccessFailure with a CLR HRESULT that looks like MXAccess E_INVALIDARG |
| WIP-006 | Low | Bug | Plausible | Time-typed value writes pass UTC clock fields as VT_DATE; only the timestamp argument got the #228 local-time fix |
| WIP-007 | Low | Bug | Confirmed (config-gated) | The watchdog ignores ShuttingDown, so a graceful shutdown longer than HeartbeatGrace raises StaHung |
| WIP-008 | Low | Bug | Confirmed | Null array elements are converted to real-looking values (0, false, "", 1970-01-01) |
| WIP-009 | Low | Bug | Plausible | No pipe read is outstanding during MXAccess startup, and the hello read has no timeout, so a hung startup outlives a dead gateway |
| WIP-010 | Low | Performance | Confirmed | The dispatcher runs the first drain step, including console logging, under its gate on the pipe read loop |
Status of the perf.md recommended fixes at HEAD
659bb831 (prototype) and 30ac3f32 (productized) are not ancestors of HEAD; they exist only on feat/worker-perf-prototype, feat/gateway-relay-hops and fix/readbulk-subscription-teardown. git grep at HEAD finds no RecordInfoPin, no mxgw-event-drain, no blocking WaitForEvents(.
perf.md item |
Present at HEAD? | Evidence |
|---|---|---|
Next step 1: pin the MXAccess type library / MXSTATUS_PROXY record info |
No | No MxStatusProxyRecordInfoPin anywhere under src/ |
| Next step 3: dedicated event-drain thread | No | Ipc/WorkerPipeSession.cs:592-661 is still an async thread-pool loop |
| 1(a): coalescing window after a wake | No | Ipc/WorkerPipeSession.cs:615-627 drains immediately on every wake |
| 1(b): one write for a whole batch | No | Ipc/WorkerFrameWriter.cs:613 and :780 still issue one WriteAsync per frame |
| 2: untimed or long event wait | No | Ipc/WorkerPipeSession.cs:23 (25 ms) used at :624-626; MxAccess/MxAccessEventQueue.cs:318-321 is WaitAsync(timeout, ct) |
| 2: raise the STA idle wait | No | Sta/StaRuntime.cs:32 is still 50 ms |
3: synchronous Flush (or none) |
No | Ipc/WorkerFrameWriter.cs:591 and :643 still call FlushAsync |
| 4: value cache signals only when a waiter exists | No | MxAccess/MxAccessValueCache.cs:127 still calls updateSignal.Set() unconditionally |
6: index MXSTATUS_PROXY[] directly |
No | Conversion/MxStatusProxyConverter.cs:65-82 still boxes through foreach (object?) into a List |
| 6: cache the wait-handle array | No | Sta/StaMessagePump.cs:27, Sta/StaWaitHelper.cs:85 allocate an IntPtr[] per wait |
| 6: typed array fast paths | No | Conversion/VariantConverter.cs:442-506 box per element |
6: reuse CalculateSize() |
Partly | The queue caches the size at enqueue (MxAccess/MxAccessEventQueue.cs:249); the writer recomputes at Ipc/WorkerFrameWriter.cs:749 |
| Gateway: pool spin limit in the Server csproj | No | No UnfairSemaphoreSpinLimit in tracked source (a stale bin/ runtimeconfig has it) |
WIP-001: Unbounded message-pump drain starves STA commands and the activity stamp
- Severity: High
- Category: Bug
- Confidence: Plausible. The mechanism is confirmed in code; the trigger rate is estimated from
perf.md. - Locations:
Sta/StaMessagePump.cs:44-56,Sta/StaRuntime.cs:335-341,Sta/StaRuntime.cs:404-423,Ipc/WorkerPipeSession.cs:1445-1493
Description. StaMessagePump.PumpPendingMessages loops while (PeekMessage(PM_REMOVE)) with no message or time bound. The STA loop calls it and only afterwards calls MarkActivity() and returns to ProcessQueuedCommands(). Nothing on the event path (MxAccessBaseEventSink.EnqueueEvent) stamps activity. While inbound messages arrive at least as fast as they dispatch, the pump never returns, so:
LastActivityUtcfreezes even though the STA is doing useful work.- Queued
InvokeAsyncwork items do not run.commandWakeEventis signalled but nothing looks at the queue. This includes the alarm poll and anyUnAdvise/RemoveItema client sends to shed load.
The watchdog (ReportWatchdogFaultIfNeededAsync) sees staleness above HeartbeatGrace (15 s) with no command in flight, sets _state = Faulted and writes WorkerFault{StaHung}. The gateway faults the session on any WorkerFault (Server/Workers/WorkerClient.cs:682-686).
Failure scenario. perf.md measures about 1.4 ms of STA time per OnDataChange on vd03 at HEAD (the record-info pin is not merged, see WIP-002). That caps dispatch near 700 events/s. A client that advises enough fast-changing tags to exceed that rate for more than 15 s gets its session killed with "STA activity is stale", a diagnosis that points at a hung COM call. The event queue never overflows because the drain loop keeps up, so the designed QueueOverflow fail-fast does not fire first. With a command in flight the same load is tolerated only until HeartbeatStuckCeiling (75 s), and that command does not start in the meantime.
Suggested fix. Bound each pump pass (for example 64 messages or about 10 ms), call MarkActivity() inside the pump loop, and interleave ProcessQueuedCommands() between slices. MWMO_INPUTAVAILABLE already makes the next wait return immediately when messages remain, so a bounded pass loses no wakeups.
Test idea. Drive StaRuntime with a fake IStaMessagePump whose PumpPendingMessages simulates a backlog that refills for N seconds. Assert that LastActivityUtc advances during the backlog and that an InvokeAsync queued mid-backlog completes before it ends.
WIP-002: None of the perf.md worker fixes are on main
- Severity: High
- Category: Performance
- Confidence: Confirmed
- Locations:
Ipc/WorkerPipeSession.cs:23,:592-661;Ipc/WorkerFrameWriter.cs:570-656,:780;MxAccess/MxAccessEventQueue.cs:318-321,:470-489;Sta/StaRuntime.cs:32
Description. The table above lists each recommendation. HEAD still has the exact path perf.md measured at 67% of a core on windev (44% on vd03) for about 240 events/s:
- Every enqueue releases the
SemaphoreSlim, which queues the drain continuation to the thread pool (MxAccessEventQueue.cs:470-489). - The drain loop writes what is almost always a one-event batch, with one overlapped
WriteFileper frame (WorkerFrameWriter.cs:780). - Each pass then calls
FlushAsync(WorkerFrameWriter.cs:643, plus:591on a control-to-event transition). On .NET Framework 4.8PipeStreamdoes not overrideFlushAsync, so this is aTask.Factory.StartNewhop around aFlushthat does no I/O. - The loop re-arms
WaitAsync(25 ms, ct), which creates and cancels a timer per wait and wakes an idle worker 40 times a second. The comment atWorkerPipeSession.cs:18-22says an idle worker "parks instead of waking 40x/s"; the code does not do that. - There is no record-info pin, so
lmxproxystill resolves the type library through the registry on every event (72% of worker CPU on vd03).
HEAD is what the deploy notes in the recent commits describe as running on DEV, QA and PROD (e74918cc lineage), so the measured cost is the production cost.
Failure scenario. A worker at about 240 events/s uses 8–12% of a 4-core box. The same STA cost is what sets the roughly 700 events/s ceiling behind WIP-001.
Suggested fix. Merge feat/worker-perf-prototype (659bb831 + 30ac3f32): pin, dedicated drain thread, synchronous Flush. Then take 1(b), a single buffer per batch, since it needs no gateway change.
Test idea. The prototype branch already carries the drain-thread completion tests. Add a writer test that counts stream Write calls for an N-frame batch and expects one.
WIP-003: Time-typed array and FILETIME conversion throws on unexpected element shapes
- Severity: Medium
- Category: Bug
- Confidence: Plausible. The throw sites are confirmed; the live element types for buffered events are undocumented.
- Locations:
Conversion/VariantConverter.cs:508-529,:363-370,:386-393; callersMxAccess/MxAccessEventMapper.cs:274-280,:339,:512-516; fault pathMxAccess/MxAccessBaseEventSink.cs:259-268
Description. When an expected element type is supplied, ConvertArray trusts it over the actual CLR element type (ResolveArrayElementDataType, :549-552). For MxDataType.Time, ConvertTimestampArray handles null and DateTime and sends everything else through Convert.ToInt64(item) followed by DateTime.FromFileTimeUtc. That throws:
FormatExceptionfor a string element. MXAccess delivers theOnDataChangetimestamp as aVT_BSTR(MxAccessEventMapper.cs:346-351), so a VARIANT array of BSTR timestamps is a credible shape forOnBufferedDataChange.ArgumentOutOfRangeExceptionfor a negative or oversizedlong, in the array path and in the scalar paths at:369and:392.- A wrong value, with no exception, for a
doubleelement (an OLE date is rounded and read as a FILETIME near 1601).
Any exception in event conversion is recorded as MxaccessEventConversionFailed and faults the session (MxAccessBaseEventSink.cs:259-268). docs/LiveCaptures-2026-11-13.md:117 records that a multi-sample OnBufferedDataChange has not been captured, so these shapes are untested against the real provider. The same applies to the buffered value array when dtDataType is Time, Boolean (Convert.ToBoolean("x")) or Integer.
Failure scenario. A client calls AddBufferedItem and SetBufferedUpdateInterval on a live tag. The first multi-sample event arrives with a timestamp array of strings. ConvertTimestampArray throws FormatException, the worker reports MxaccessEventConversionFailed, and every subscription on that session is lost.
Suggested fix. Make typed-array conversion total. On an element that does not match the expected type, fall back to the array's actual element type, or to the RawValues projection with RawDiagnostic, which the default branch already implements. Parse string timestamps with the mapper's TryParseSourceTimestamp. Guard FromFileTimeUtc with a range check and fall back to the integer projection.
Test idea. VariantConverter.ConvertArray(new object[] { "3/26/2026 1:38:22.907 PM" }, MxDataType.Time) and Convert(-1L, MxDataType.Time) must not throw. CreateOnBufferedDataChange with string timestamps must return an event.
WIP-004: Integer array conversion narrows to int and overflows
- Severity: Medium
- Category: Bug
- Confidence: Confirmed by reading; the trigger is unlikely with stock MXAccess types.
- Locations:
Conversion/VariantConverter.cs:110-120,:453-462,:464-473,:559-569
Description. The scalar path widens uint to Int64Value and projects ulong above long.MaxValue to a raw value (:296-301, :381-407). The array path does neither. ResolveArrayElementDataType maps uint[] to Integer, and ConvertArray sends everything except long[]/ulong[] to ConvertInt32Array, which calls Convert.ToInt32(item). A uint element above int.MaxValue throws OverflowException. So does a long element inside an object[] (SAFEARRAY of VARIANT) when the expected type is Integer, and a ulong[] element above long.MaxValue in ConvertInt64Array. As in WIP-003, the exception faults the session when it happens on the event path.
Failure scenario. An attribute or buffered sample set arrives as SAFEARRAY(VT_UI4) containing 0x80000000 or larger (a bitmask, for example). The data-change event throws during conversion and the session faults.
Suggested fix. Choose the 64-bit projection for uint[] and for object[], or widen per element on overflow. Mirror the scalar raw fallback for ulong above long.MaxValue.
Test idea. ConvertArray(new uint[] { uint.MaxValue }), ConvertArray(new object[] { 5_000_000_000L }, MxDataType.Integer) and ConvertArray(new ulong[] { ulong.MaxValue }) return without throwing and preserve the values.
WIP-005: Worker-side validation exceptions are returned as MxaccessFailure
- Severity: Medium
- Category: Bug
- Confidence: Confirmed
- Locations:
Conversion/HResultConverter.cs:19-43,Sta/StaCommandDispatcher.cs:293-296,:409-420; throw sitesConversion/VariantConverter.cs:178-181,:260-263; call sitesMxAccess/MxAccessCommandExecutor.cs:458,:499-500,:540
Description. ExecuteWrite and its siblings call variantConverter.ConvertToComValue(...) inline as an argument to session.Write(...). For an MxValue with no kind set, a raw payload, or an MxArray with no values, the converter throws ArgumentException. That propagates to StaCommandDispatcher.ExecuteQueuedCommandAsync, which maps every exception through HResultConverter.Convert: ProtocolStatusCode.MxaccessFailure with Hresult = exception.HResult. For ArgumentException that is 0x80070057, the same number as COM E_INVALIDARG. The client cannot tell a request it built wrongly from MXAccess rejecting the write, and no MXAccess call was made. The same mapping covers StaRuntimeShutdownException and the "STA loop terminated" InvalidOperationException from StaRuntime.InvokeAsync, which reach clients as MXAccess failures with CLR HRESULTs.
Failure scenario. A client sends Write with value = MxValue{} (data type set, no kind). The reply is MxaccessFailure, HRESULT 0x80070057. The operator investigates the Galaxy attribute; the real cause is a malformed request. This breaks the parity contract in the other direction: an HRESULT is reported that MXAccess never produced.
Suggested fix. In the dispatcher's catch, treat only COMException (and other exceptions known to come out of the interop call) as MxaccessFailure. Map ArgumentException to InvalidRequest without an HRESULT, and StaRuntimeShutdownException/loop-fault to WorkerUnavailable. Alternatively validate the value in the executor before the call, as the "value is required" checks already do.
Test idea. Dispatcher test with an executor that throws ArgumentException: expect InvalidRequest and HasHresult == false. Executor test: Write with an empty MxValue returns InvalidRequest.
WIP-006: Time-typed value writes pass UTC clock fields as VT_DATE
- Severity: Low
- Category: Bug
- Confidence: Plausible. Needs a live check; the asymmetry is confirmed in code.
- Locations:
Conversion/VariantConverter.cs:174-176,:258-259(write),:219-246(timestamp argument),:594-604(read)
Description. #228 established that MXAccess reads a VT_DATE as box-local time and that the COM marshaler ignores DateTime.Kind. ConvertToComTimestamp was fixed to convert to local time. The value of a write still goes through ConvertToComValue, where TimestampValue => value.TimestampValue.ToDateTime() produces a UTC DateTime whose clock fields are marshaled unchanged. If MXAccess applies the same local-time reading to a Time-typed attribute value as it does to the time argument, a written instant is stored shifted by the box's UTC offset. ConvertToComArray has the same shape for timestamp arrays. On the read side ToTimestamp labels an Unspecified-kind VT_DATE as UTC, so a gateway round trip hides the shift while other MXAccess clients see it.
Failure scenario. On a UTC-5 box a client writes 2026-12-02T15:00:00Z to a Time attribute. MXAccess stores 20:00Z. InTouch shows the value five hours late; reading back through the gateway may show 15:00Z.
Suggested fix. Capture one live write and read of a Time attribute against a second MXAccess client. If the shift is real, route TimestampValue writes through ToMxAccessLocalTime and convert VT_DATE reads from local to UTC with the same zone.
Test idea. Live MXAccess fact: write a known UTC instant to a Time attribute, read it back through the gateway and through MxTraceHarness, compare both to the instant.
WIP-007: The watchdog ignores ShuttingDown
- Severity: Low
- Category: Bug
- Confidence: Confirmed mechanism. Reachable only when the shutdown grace exceeds
HeartbeatGrace. - Locations:
Ipc/WorkerPipeSession.cs:1218-1249,:1396-1425,:1445-1493;Sta/StaRuntime.cs:404-411
Description. During ShutdownAsync the heartbeat loop keeps running and ReportWatchdogFaultIfNeededAsync does not check _state. Graceful cleanup runs as one STA work item (staRuntime.InvokeAsync(() => session.ShutdownGracefully())). StaRuntime stamps activity only before and after a work item, the dispatcher's CurrentCommandCorrelationId is empty and StaCallInProgress is false. If cleanup takes longer than HeartbeatGrace, the watchdog overwrites ShuttingDown with Faulted and writes WorkerFault{StaHung}. The gateway then records a fault for a session that was closing cleanly. The default grace is 10 s (Server/Configuration/WorkerOptions.cs:43) against a 15 s HeartbeatGrace, so defaults are safe.
Failure scenario. An operator raises ShutdownTimeoutSeconds to 60 for a session with tens of thousands of advised items. Unadvise and remove take 25 s. At the first heartbeat after 15 s the worker reports StaHung, and the close is logged as a worker fault.
Suggested fix. Return early from the watchdog when _state is ShuttingDown or Stopped, or have the shutdown work item advertise itself the way the alarm poll does through StaCallInProgress.
Test idea. Session test with a fake runtime whose ShutdownGracefullyAsync takes longer than a short HeartbeatGrace: assert no WorkerFault frame is written and a WorkerShutdownAck is.
WIP-008: Null array elements become real-looking values
- Severity: Low
- Category: Bug
- Confidence: Confirmed
- Locations:
Conversion/VariantConverter.cs:447,:458,:469,:480,:491,:502,:513-516
Description. A null element in a VARIANT array (VT_EMPTY/VT_NULL) is converted to false, 0, 0.0, "" or the Unix epoch. A scalar null is reported honestly through IsNull (:409-419); the array path has no equivalent, so the client receives a fabricated sample it cannot tell from a real one. For buffered data this means an invented timestamp of 1970-01-01 paired with a real value.
Failure scenario. A buffered sample set carries a missing timestamp for one sample. The client receives 1970-01-01T00:00:00Z for it and a historian stores the point at the epoch.
Suggested fix. When any element is null, use the raw projection with a RawDiagnostic naming the null indices, or add a null mask to MxArray (a contract change). Either way, do not emit a default value without marking it.
Test idea. ConvertArray(new object?[] { 1, null }, MxDataType.Integer) yields a result that marks index 1 as null.
WIP-009: A hung startup outlives a dead gateway
- Severity: Low
- Category: Bug
- Confidence: Plausible
- Locations:
Ipc/WorkerPipeSession.cs:349-359,Ipc/WorkerFrameReader.cs:117-125,WorkerApplication.cs:155
Description. Gateway death is detected only by a pipe read returning zero bytes or a write failing. In CompleteStartupHandshakeAsync there are two windows without that signal:
- The first
_reader.ReadAsyncwaits forGatewayHellowith no timeout, and net48 pipe reads ignore the token. A peer that connects and never sends keeps the worker alive indefinitely. - After the hello is read, no read is outstanding while
initializeMxAccessAsyncruns. If COM activation hangs on the STA and the gateway dies or abandons the launch, nothing in the worker notices.WorkerApplication.Runpasses no cancellation token, so nothing else ends the wait.
The gateway kills workers it still tracks and sweeps orphans at its next start, so this matters when the gateway process is gone and not restarted, or the sweep does not match the process.
Failure scenario. MXAccess activation blocks (provider down). The gateway's startup timeout fires and it is then stopped for a deploy before it kills the worker. The x86 worker stays alive holding a half-created LMXProxyServer until someone kills it by hand.
Suggested fix. Bound the handshake with a worker-side deadline (reuse the launch timeout passed in the environment) and exit with PipeConnectionFailed when it expires. Optionally pass the gateway PID and watch the process handle.
Test idea. Session test with a stream that never yields a hello and a short handshake deadline: RunAsync must fail within the deadline.
WIP-010: The dispatcher runs its first drain step under its gate on the pipe read loop
- Severity: Low
- Category: Performance
- Confidence: Confirmed
- Locations:
Sta/StaCommandDispatcher.cs:125-153,:243-261,:263-289,:312-327
Description. DispatchAsync calls _ = DrainAsync() while holding gate. An async method runs synchronously to its first incomplete await, so on the caller's thread and under the lock it dequeues, calls LogCommandStarted (a synchronous Console.Error.WriteLine when MXGATEWAY_WORKER_LOG_COMMANDS is on) and calls staRuntime.InvokeAsync. The caller is ProcessCommandAsync, started synchronously from the pipe message loop (Ipc/WorkerPipeSession.cs:765, :1270). PopulateHeartbeat, PendingCommandCount, CurrentCommandCorrelationId and CancelQueuedCommand take the same lock, so a slow stderr sink stalls the read loop, heartbeat capture and WorkerCancel handling together.
Failure scenario. Command logging is enabled for diagnosis and the worker's inherited stderr is a slow or full sink. Each command dispatch blocks the read loop and the heartbeat's snapshot behind a console write.
Suggested fix. Set drainActive under the lock and start DrainAsync after releasing it (or begin it with await Task.Yield()), so logging and the STA enqueue run outside gate.
Test idea. Dispatcher test with a CommandLogger that blocks on a gate: PendingCommandCount and CancelQueuedCommand on another thread must return while the logger is blocked.
Checked and found sound
- Frame writer (
Ipc/WorkerFrameWriter.cs): single write lock, claim/tombstone interlock under_gate, detached lock waits always drain and release, stream failures fail every queued frame, the pooled buffer is returned only after the write completes, sequence is committed only before the write. - Frame reader (
Ipc/WorkerFrameReader.cs): partial reads loop to completion, zero and oversized lengths are rejected before renting, zero-byte reads map toEndOfStream, single-consumer invariant holds through teardown. - STA wake handoff (
Sta/StaRuntime.cs): theAutoResetEventstays signalled if set between the last dequeue and the wait, so no wakeup is lost. Enqueue and the shutdown/fault flags sharegate, so no item is enqueued after the final cancel sweep. StaWorkItem: cancel-versus-execute is settled by oneCompareExchange; continuations run asynchronously, so nothing runs inline on the STA.- Loop-fault handler registration: fires exactly once whichever side wins the race.
- Log redaction (
Bootstrap/WorkerLogRedactor.cs): thenoncefield logged atWorkerApplication.cs:152is redacted by field name.