Files
mxaccessgw/code-reviews/2026-12-02-perf-bugs/worker-mxaccess.md
T

22 KiB

Worker MxAccess Review: Bugs and Performance (2026-12-02)

Scope: src/ZB.MOM.WW.MxGateway.Worker/MxAccess/ at main 54367e74. Read-only review. Other worker code (Sta/, Ipc/WorkerPipeSession.cs) and GatewayAlarmMonitor.cs were read only to confirm findings. Nothing was built or run; every finding rests on reading the code.

Paths below are relative to src/ZB.MOM.WW.MxGateway.Worker/.

Summary

ID Severity Category Confidence Title
MXA-001 High Bug Confirmed Alarm failover never engages (or falsely "recovers") when the wnwrap primary fails to subscribe
MXA-002 High Performance Confirmed perf.md worker fixes (record-info pin, drain thread, sync flush) are not on main
MXA-003 Medium Bug Confirmed Graceful-shutdown timeout does not cover the alarm poll join or alarm handler dispose
MXA-004 Medium Bug Plausible Late callbacks re-create value/completion cache entries that are never evicted
MXA-005 Medium Bug Plausible Subtag fallback ignores quality; a null or bad-quality update reads as a Clear
MXA-006 Medium Bug Confirmed (tracked #238) ReadBulk teardown can remove a caller-held item; fix is on an unmerged branch
MXA-007 Low Bug Plausible Subtag state machine loses an existing ack when Acked arrives before InAlarm
MXA-008 Low Performance Plausible wnwrap poll re-fetches and re-parses the full alarm XML every 500 ms
MXA-009 Low Performance Confirmed STA completion waits tick every 5 ms and rescan every pending handle per wake
MXA-010 Low Performance Plausible Subtag source and ack writer tear down item by item before Unregister
MXA-011 Low Performance Confirmed Alarm poll loop wakes the STA every 500 ms with no alarm subscription

Status of the perf.md recommendations

Checked against main 54367e74:

perf.md item On main? Evidence
Type-library / MXSTATUS_PROXY record-info pin No No MxStatusProxyRecordInfoPin, LoadRegTypeLib or GetRecordInfoFromGuids anywhere in the worker. MxAccess/MxAccessComObjectFactory.cs:9-12 is still a bare new LMXProxyServerClass().
Dedicated event-drain thread No No mxgw-event-drain thread and no blocking WaitForEvents. MxAccess/MxAccessEventQueue.cs:318-321 still exposes only SemaphoreSlim.WaitAsync(timeout, ct).
Synchronous pipe flush No Ipc/WorkerFrameWriter.cs:591,643 still call _stream.FlushAsync.
Value-cache Set() only when a waiter exists (finding 4) No MxAccess/MxAccessValueCache.cs:127 signals unconditionally.
Timestamp memoisation (finding 5) No MxAccess/MxAccessEventMapper.cs:397-421 parses per event.

The prototype commits (659bb831, 30ac3f32) exist only on local branches feat/worker-perf-prototype, feat/gateway-relay-hops and fix/readbulk-subscription-teardown. See MXA-002.

Findings

MXA-001: Alarm failover never engages (or falsely "recovers") when the wnwrap primary fails to subscribe

  • Severity: High
  • Category: Bug
  • Confidence: Confirmed (code path); not run against live wnwrap
  • Locations:
    • MxAccess/WnWrapAlarmConsumer.cs:355-363 (PollOnce returns silently when !subscribed)
    • MxAccess/WnWrapAlarmConsumer.cs:188-281 (subscribed = true only at the end of Subscribe)
    • MxAccess/FailoverAlarmConsumer.cs:137-157 (Subscribe), :291-309 (RunPrimary), :223-259 (ProbeOnce)
    • MxAccess/AlarmCommandHandler.cs:253-257 (default threshold 3, stable probes 3)

Description. FailoverAlarmConsumer.Subscribe routes the primary's Subscribe through RunPrimary, which swallows the exception and counts one failure. WnWrapAlarmConsumer.Subscribe sets subscribed = true only after all four wnwrap calls succeed, so after a failure it stays false. From then on WnWrapAlarmConsumer.PollOnce returns at if (disposed || !subscribed) return; without touching COM. RunPrimary treats that silent return as success and resets consecutiveFailures to 0. ProbeOnce treats it as a clean probe. Nothing ever re-subscribes the primary (ProbeOnce deliberately does not).

Failure scenario.

  • Default threshold (3): the alarm manager is unavailable when SubscribeAlarms runs, so InitializeConsumer/RegisterConsumer/Subscribe return non-zero or SetXmlAlarmQuery throws. That is failure 1 of 3. Every later poll is a no-op "success", so the counter never reaches 3. The consumer stays in Alarmmgr mode with a dead primary: no transitions, an empty QueryActiveAlarms snapshot, no OnAlarmProviderModeChanged, and no fault. The subtag standby is armed but gated off.
  • Threshold 1: the subscribe failure switches to standby. After FailbackStableProbes no-op probes (about 90 s at the defaults) the consumer announces "recovered" and switches back to the dead primary. The gateway then reconciles against an empty snapshot and clears every alarm the standby had reported.

The unit tests miss this because the fake primary in FailoverAlarmConsumerTests throws from PollOnce while unhealthy; the production consumer does not.

Suggested fix. Make an unsubscribed primary count as unhealthy: either have WnWrapAlarmConsumer.PollOnce throw when Subscribe was attempted and failed, or have FailoverAlarmConsumer track primarySubscribed and retry primary.Subscribe in PollOnce/ProbeOnce (counting failures) instead of polling. A failed subscribe needs wnwrap deregistered first, or a fresh consumer instance.

Test idea. A primary fake whose Subscribe throws and whose PollOnce is a no-op (the wnwrap shape). Assert that after Threshold poll ticks the mode is Subtag, and that ProbeOnce never fails back until a Subscribe succeeds.

MXA-002: perf.md worker fixes are not on main

  • Severity: High
  • Category: Performance
  • Confidence: Confirmed
  • Locations: MxAccess/MxAccessComObjectFactory.cs:9-12; MxAccess/MxAccessEventQueue.cs:318-321; Ipc/WorkerFrameWriter.cs:591,643; MxAccess/LmxSubtagAlarmSource.cs:239; MxAccess/AlarmAckWriter.cs:383

Description. perf.md measured worker CPU at 67% of a core at ~240 events/s, falling to ~6% with the record-info pin plus the dedicated drain thread. Neither change is on main (see the status table above), so the deployed line still pays the per-event GetRecordInfoFromGuids registry/typelib lookup on the STA and the per-event thread-pool wake-ups.

One point perf.md does not state: the worker creates up to three LMXProxyServerClass instances through the same factory (session, LmxSubtagAlarmSource, AlarmAckWriter). The standby subtag source is armed whenever fallback is enabled and advises three subtags per watched alarm, so its OnDataChange callbacks pay the same unpinned per-event cost on the shared STA.

Failure scenario. Any worker at a few hundred events/s uses most of a core, and proportionally more on hosts with CrowdStrike (vd03).

Suggested fix. Merge the productized prototype (30ac3f32). Keep the pin in MxAccessComObjectFactory.Create() so all three COM instances benefit, since it is per process.

Test idea. Existing prototype tests plus the bench-run.ps1 comparison in perf.md; assert WorkerReady.record_info_pin_status reports success on windev.

MXA-003: Graceful-shutdown timeout does not cover the alarm poll join or alarm handler dispose

  • Severity: Medium
  • Category: Bug
  • Confidence: Confirmed (code path)
  • Locations: MxAccess/MxAccessStaSession.cs:773-813 (unbounded awaits), :815-835 (timeout machinery starts after them); caller Ipc/WorkerPipeSession.cs:1236-1238

Description. ShutdownGracefullyAsync(timeout) does two awaits before it starts its Stopwatch and Task.WhenAny(cleanupTask, delayTask):

  1. await pollTaskToAwait (line 784). If the poll loop is inside staRuntime.InvokeAsync(PollOnce) and that work item has started, cancellation cannot complete it (StaWorkItem only cancels before execution).
  2. await staRuntime.InvokeAsync(() => alarmHandlerToDispose.Dispose(), cancellationToken) (lines 805-807). The token is the session token, not the grace period, and it also only cancels a not-yet-started item.

Production always passes an alarm handler factory (Ipc/WorkerPipeSession.cs:1631-1632), so both awaits always run.

Failure scenario. The STA is stuck in a COM call (a hung Write, a hung GetXmlCurrentAlarms2, or a long ReadBulk) when WorkerShutdown arrives. Step 2 queues behind the stuck work item and never completes. ShutdownGracefullyAsync never reaches its timeout, so no TimeoutException, no shutdown-timeout WorkerFault, and no ShutdownAck. The worker sits until the gateway's own kill path fires. A hung STA is exactly the case the grace period exists for.

Suggested fix. Start the stopwatch at the top and bound both awaits with the remaining grace (Task.WhenAny against a delay), then throw the same TimeoutException.

Test idea. A session with an alarm handler and a work item that blocks the STA on a ManualResetEvent. Assert ShutdownGracefullyAsync(200 ms) throws TimeoutException within roughly the grace period.

MXA-004: Late callbacks re-create value/completion cache entries that are never evicted

  • Severity: Medium
  • Category: Bug (memory growth)
  • Confidence: Plausible. The mechanism is in the code and its comments; the growth rate was not measured.
  • Locations:
    • MxAccess/MxAccessBaseEventSink.cs:147-156 and :177-183 (cache write on every callback, no registry check)
    • MxAccess/MxAccessSession.cs:291-302 (EvictStaleHandleState), :307-324 (RemoveItem), :1154-1182 (TearDownSnapshots)
    • MxAccess/AlarmAckWriter.cs:160-171 (handles are never reused within a registration)

Description. OnDataChange and OnWriteComplete write into MxAccessValueCache / MxAccessWriteCompletionCache for any handle pair, live or not. RemoveItem evicts the entries, but the comment on EvictStaleHandleState states that a callback already queued on the STA is dispatched afterwards and re-creates the entry. The only later eviction for that key is EvictStaleHandleState, which runs when MXAccess hands the same handle id out again. AlarmAckWriter's comment records a live probe (windev, 2026-10-20) showing item handles strictly increase within a registration and are never reused. So a re-created entry stays until Unregister.

AlarmAckWriter already guards against this with heldItemHandles (:430-437); the session sink has no equivalent.

Failure scenario. A client polls ReadBulk for uncached, fast-changing tags. Each call does AddItem, Advise, wait, UnAdvise, RemoveItem. When a second data change for a snapshot handle is posted before UnAdvise, it is dispatched after RemoveItem and leaves one orphaned CachedValue (retaining the event's MxValue, Timestamp and status rows) under a handle id that will never recur. The same happens for ordinary subscribe/unsubscribe churn. Over days, in a 32-bit process, this is unbounded growth; RemoveServer also scans the whole dictionary.

Suggested fix. In the sink's post-publish hooks, skip the cache write when HandleRegistry.ContainsItemHandle(server, item) is false. The registry is STA-only and so are the callbacks, so no lock is needed. This also lets EvictStaleHandleState go.

Test idea. With the production sink over a fake COM server: AddItem, RemoveItem, then invoke OnDataChange for the removed handle. Assert ValueCache.Count == 0 (and the same for OnWriteComplete).

MXA-005: Subtag fallback ignores quality; a null or bad-quality update reads as a Clear

  • Severity: Medium
  • Category: Bug
  • Confidence: Plausible. The code drops quality unconditionally; what MXAccess delivers for the alarm subtags on comms loss was not observed.
  • Locations: MxAccess/LmxSubtagAlarmSource.cs:285-294 (quality discarded), :153-178; MxAccess/SubtagAlarmStateMachine.cs:76-96, :212-217 (null coerces to false), :137-148

Description. LmxSubtagAlarmSource.OnDataChange receives pwItemQuality and drops it. SubtagAlarmStateMachine.Apply coerces the value alone, and CoerceBool(null) is false. An InAlarm update with an empty value therefore takes the true-to-false branch and emits UNACK_RTN/ACK_RTN, and the alarm leaves SnapshotActive().

Failure scenario. The worker is in subtag mode because the alarm provider is degraded. An object's engine goes off scan or the reference becomes unresolved, and MXAccess delivers the InAlarm subtag with bad quality and an empty value. Every active alarm on that object is reported cleared, and the gateway's reconcile pass confirms the clear from the snapshot. The same applies to the initial bad-quality callback some references deliver before the first good value, though that case is a no-op because the state starts inactive.

Suggested fix. Pass quality into SubtagValueChange and have the state machine ignore non-good updates (keep the last known state), or at minimum ignore a null value.

Test idea. Raise an alarm through the state machine, then apply the InAlarm address with value: null and a bad quality. Assert no transition and that SnapshotActive() still lists the alarm.

MXA-006: ReadBulk teardown can remove a caller-held item; fix is on an unmerged branch

  • Severity: Medium
  • Category: Bug
  • Confidence: Confirmed on main; already tracked as #238
  • Locations: MxAccess/MxAccessSession.cs:1057-1069 (AddItem/Advise for uncached tags), :1154-1182 (TearDownSnapshots removes every non-zero handle)

Description. For a tag the caller has added but that has no cached value yet (added-only, or advised with the first OnDataChange still pending), ReadBulk takes the snapshot path. If MXAccess returns the caller's existing handle from AddItem, the teardown UnAdvises and RemoveItems it. The fix (7a41d9ed, 2e6645ef, cc33b063, with a live repro in 13e9a26d) is on fix/238-readbulk-teardown and is not on main.

Failure scenario. A client subscribes to a tag and immediately issues ReadBulk for it before the first data change. Its subscription is silently torn down and it receives no further events for that handle.

Suggested fix. Merge fix/238-readbulk-teardown.

Test idea. Covered by the branch's MxAccessSessionTests additions and the live smoke test.

MXA-007: Subtag state machine loses an existing ack when Acked arrives before InAlarm

  • Severity: Low
  • Category: Bug
  • Confidence: Plausible. The logic is confirmed; it depends on MXAccess's initial callback order.
  • Locations: MxAccess/SubtagAlarmStateMachine.cs:127-135 (state.Acked = false on raise), :159-178

Description. On a false-to-true InAlarm, ApplyActive unconditionally resets Acked and AckedDuringEpisode. That is right for a re-raise. It is wrong for the initial sync of an alarm that is already active and acknowledged, if the Acked = true value is delivered first: it is stored, then wiped by the InAlarm = true update. No further Acked change arrives because the Galaxy value has not changed.

Failure scenario. After failover the standby reports an acknowledged alarm as UNACK_ALM in QueryActiveAlarms, and later reports its return as UNACK_RTN. It stays wrong until the operator acks again or the alarm clears. SubtagAlarmConsumer.Subscribe advises Active before Acked, which makes the good order likely but not guaranteed.

Suggested fix. Track the last raw Acked value and when it was received separately from the episode state. On raise, keep Acked = true if no raise has been seen since that value arrived during this subscription (the initial-sync case).

Test idea. Apply(acked, true) then Apply(active, true) on a fresh state machine. Assert the snapshot state is AckAlm.

MXA-008: wnwrap poll re-fetches and re-parses the full alarm XML every 500 ms

  • Severity: Low
  • Category: Performance
  • Confidence: Plausible. The allocation pattern is confirmed; the cost at scale was not measured.
  • Locations: MxAccess/WnWrapAlarmConsumer.cs:365-370, :680-841

Description. Each poll marshals the whole GetXmlCurrentAlarms2 BSTR into a new string and parses every record into about 19 strings plus a record object, then diffs. This happens on the STA at 2 Hz whether or not anything changed. With roughly 150 or more standing alarms the XML string exceeds 85 KB and lands on the large object heap on every poll.

Failure scenario. A site with several hundred standing alarms allocates a multi-hundred-KB LOH string plus thousands of small strings twice a second. In an x86 process that drives frequent gen-2 collections and STA pauses that delay OnDataChange dispatch.

Suggested fix. Keep the previous XML string and skip the parse and diff when the new one is ordinally equal (still record the truncation verdict). The BSTR copy itself cannot be avoided.

Test idea. Extract the fetch-to-fold step behind a seam, feed the same XML twice, and assert the parser runs once and no transitions are emitted.

MXA-009: STA completion waits tick every 5 ms and rescan every pending handle per wake

  • Severity: Low
  • Category: Performance
  • Confidence: Confirmed
  • Locations: MxAccess/MxAccessValueCache.cs:299-383 (pollIntervalMs = 5, full rescan at :353-366); MxAccess/MxAccessWriteCompletionCache.cs:138-185; callers MxAccess/MxAccessSession.cs:1119, MxAccess/MxAccessCommandExecutor.cs:1128

Description. Both wait loops default to a 5 ms fallback tick and no caller overrides it (the comments describe a 50 ms fallback, which is only the clamp ceiling). Every wake, whether from the tick or from any window message, runs pumpStep and then TryWaitForUpdates re-probes every outstanding handle with a lock and a dictionary lookup each.

Failure scenario. A ReadBulk of several thousand tags where some never deliver, on a session already receiving ~240 events/s, wakes about 440 times/s and performs millions of lock-and-lookup operations per second on the STA for the full timeout. An unconfirmed Write costs up to 300 wake-ups over its 1.5 s wait.

Suggested fix. Raise the fallback tick to the documented 50 ms; the message wake already provides the latency. For the bulk wait, keep a compacted list of pending indexes, or have Set record updated keys for the waiter.

Test idea. Count pumpStep invocations for a wait that times out after 200 ms with no messages; assert it is near 4, not 40.

MXA-010: Subtag source and ack writer tear down item by item before Unregister

  • Severity: Low
  • Category: Performance
  • Confidence: Plausible. The call pattern is confirmed; per-call cost was not measured.
  • Locations: MxAccess/LmxSubtagAlarmSource.cs:197-212; MxAccess/AlarmAckWriter.cs:318-328; MxAccess/FailoverAlarmConsumer.cs:113-134; MxAccess/MxAccessStaSession.cs:893-904

Description. LmxSubtagAlarmSource.Dispose issues UnAdvise and RemoveItem for every advised subtag (three per watched alarm) and then Unregister. MxAccessSession deliberately relies on Unregister alone to drop a server's items (MxAccessSession.cs:225-229, :1351-1356). UpdateAlarmWatchList replaces the standby by building a whole new COM object, re-advising everything, and disposing the old one this way.

Failure scenario. A watch list of 2,000 alarms means about 12,000 COM calls on the STA at shutdown or on a watch-list change. Data callbacks and commands wait behind them. On the non-graceful path, MxAccessStaSession.Dispose gives the alarm handler 2 s, so the session dispose queues behind the remainder and its own 2 s wait can also expire.

Suggested fix. Call Unregister only, as the session does. For ReplaceStandby, diff the watch list and advise/unadvise the delta on the existing source.

Test idea. A fake IMxAccessServer counting calls: dispose a source with N advised items and assert one Unregister and zero per-item calls.

MXA-011: Alarm poll loop wakes the STA every 500 ms with no alarm subscription

  • Severity: Low
  • Category: Performance
  • Confidence: Confirmed
  • Locations: MxAccess/MxAccessStaSession.cs:393-397, :402-447; MxAccess/AlarmCommandHandler.cs:404-411

Description. The poll loop starts at session start whenever a handler factory exists, which is always in production. Before SubscribeAlarms (and for sessions that never subscribe) each tick still creates a Task.Delay timer, a thread-pool continuation, an STA work item and a commandWakeEvent.Set(), only for PollOnce to find no dispatcher.

Failure scenario. Every idle worker takes two extra thread-pool wake-ups and two STA wakes per second. perf.md finding B shows each pool wake-up on .NET Framework costs a spin episode, so this is small but constant across all workers.

Suggested fix. Start the loop on the first successful Subscribe and stop it on Unsubscribe, or skip the STA hop when IsSubscribed is false.

Test idea. With a counting handler, start a session, wait a few intervals without subscribing, and assert no PollOnce work items were queued.

Checked and found clean

  • COM calls off the STA. None found. Commands, alarm polls, handle-registry reads and all disposal paths go through StaRuntime.InvokeAsync; the alarm path also asserts thread affinity.
  • Exceptions escaping COM event sinks. MxAccessBaseEventSink.EnqueueEvent and MxAccessAlarmEventSink.EnqueueTransition catch and convert to a queue fault. The subtag path's coercions catch their conversion exceptions.
  • Handle registry. STA-only, secondary indexes are maintained on every mutation, and the sorted views are array snapshots, so shutdown iteration while removing is safe.
  • Event queue. Bounded by count with fail-fast overflow; signalling is outside the lock.
  • COM release. Session, subtag source, ack writer and wnwrap consumer each detach events and then FinalReleaseComObject; failed creation paths release as well.
  • Write-completion correlation. The stale-completion ambiguity is documented in MxAccessCommandExecutor.cs:1067-1115 as inherent to MXAccess and was not re-reported.
  • Secrets. No password, WriteSecured value or operator_password reaches a log or diagnostic string in this folder.