docs: add worker event-path performance analysis as docs/WorkerEventPathPerformance.md (D6, #236)

This commit is contained in:
Joseph Doherty
2026-12-03 09:36:36 -05:00
parent e934854a89
commit 8d1dd7f41d
+326
View File
@@ -0,0 +1,326 @@
# Worker + gRPC Relay Performance Review (2026-11-21)
## Symptom
A single MXAccess worker handling ~240 data-change updates/sec used 8–12% of total system CPU.
## Method
1. **Code review.** Four parallel read-only investigations of the code (STA pump/handoff, worker IPC write path, worker event conversion, gateway relay). The key claims were spot-checked directly. Items marked *inferred* rest on .NET Framework 4.8 BCL behaviour rather than this repo's code.
2. **Live counters on wonder-app-vd03.** Per-process and per-thread `typeperf` counters; see [Live Capture](#live-capture-wonder-app-vd03-2026-11-21).
3. **WPR CPU trace on vd03**, analysed on windev; see [WPR Trace](#wpr-trace-wonder-app-vd03-2026-11-21). The trace overturned the code review's ranking.
## Summary
The 8–12% is reproduced on vd03. One worker (PID 20376) uses about 44% of one core, roughly 11% of the 4-core box. Two thirds of that is kernel time. The WPR trace splits the worker's CPU as follows:
- **72%: STA thread, inside MXAccess, not our code.** On every `OnDataChange`, MXAccess's proxy (`lmxproxy.dll`) builds the event's `MXSTATUS_PROXY` array. To do so it calls `oleaut32!GetRecordInfoFromGuids`, which resolves the type library through the registry each time. The worker is x86 under WOW64, so every registry path is redirected, and CrowdStrike's kernel driver (`csagent.sys`) then inspects every key open. That driver alone accounts for about 40% of the STA's samples. Each event costs about 1.4 ms of STA CPU, mostly in the kernel, which is why kernel time is twice user time. Our pump code barely appears; it only dispatches the window message.
- **26%: CLR thread-pool spin, our code.** Each per-event work item we queue (the `SemaphoreSlim` wake, pipe I/O completion, `FlushAsync`) wakes a .NET Framework thread-pool worker. When it finds no more work, the worker spins through dozens of `SleepEx` calls before parking. That is about 150 context switches per event, far more than the code review's estimate of 3–4 hops.
The code-review findings below, especially 1–3 (made worse by `f4a6cb1d`, 2026-08-15, "signal-driven event drain", which is in the deployed `e74918cc`), are the source of the 26%. None of them touch the 72%.
### Next steps
> **Update:** items 1 and 3 are prototyped and measured on windev. Worker CPU fell from 67% to 6% of a core at ~240 events/s; see [Prototype Results](#prototype-results-windev-2026-11-21). Item 4 is analysed; see [Gateway Investigation](#gateway-investigation-vd03-trace-2026-11-21).
1. **Pin the type library (worker change, try first).** At startup, on the STA, call `LoadRegTypeLib` for the MXAccess type library that defines `MXSTATUS_PROXY`, then `GetRecordInfoFromGuids`, and hold both for the process lifetime.
- This should remove the repeated library load and file open, about 28% of the STA's samples.
- The `GetTypeLibPathFromRegistry` registry reads will probably remain.
- Measure on windev under a ~240/s load first.
2. **Ask Security for a CrowdStrike exclusion** for `MxGateway.Worker.exe` (registry and file monitoring). That should remove `csagent.sys`'s ~40% share. windev has no CrowdStrike, so the same load there shows the cost without it.
3. **Take event draining off the thread pool (our fix).** A dedicated writer thread that blocks on a kernel event and writes to the pipe synchronously stops the per-event pool wake-ups. Cheaper partial fixes: a 2–5 ms coalescing window before draining, dropping `FlushAsync`, and an untimed wait.
4. **Look at the gateway.** `MxGateway.Server` had the most context switches on vd03 (240k in the trace) and probably shows the same thread-pool pattern. It was not analysed.
### Caveats
- The trace lost ~1.1M events, because vd03 runs at ~136k context switches/s. The lost events are mostly CSwitch records, so the CPU proportions still hold.
- ArchestrA modules have no PDBs. MXAccess frames are `module!0xaddr`, and the `lmxproxy` → `GetRecordInfoFromGuids` attribution rests on the module boundary, not on function names.
- One frame attributes the `DispatchMessage` P/Invoke IL stub to `CrowdStrike.Sensor.ScriptControl`. Dynamic IL stubs have no module of their own, so this is probably a module-attribution artefact. The `csagent.sys` kernel frames are real.
## Worker: Per-Event Thread-Pool Wake-Ups (source of the 26%)
### 1. One event at a time to the pipe
- Before `f4a6cb1d` the drain loop slept 25 ms, so about 6 events went out per batch at 240/s.
- Now `MxAccessEventQueue.SignalWake` (`MxAccessEventQueue.cs:~243,470`) wakes the drain loop (`WorkerPipeSession.cs:615-645`) on every enqueue. Almost every batch holds one event; `EventDrainBatchSize = 128` almost never fills.
- Each event then pays roughly:
1. `SemaphoreSlim.Release()` queues the waiter to the thread pool. This is deliberate, to keep the write off the STA (see the comment at `MxAccessEventQueue.cs:95`), and should stay.
2. An overlapped `WriteFile` (`WorkerFrameWriter.cs:780`). Its completion returns through the I/O completion port and wakes another thread.
3. `FlushAsync`: another thread-pool hop for no work (finding 3).
4. A new timed wait, with its own timer (finding 2).
- Even when a real batch forms, the writer still issues one `WriteAsync` per frame. Only the flush is shared.
- **Fix:**
- (a) Add a coalescing window after a wake: wait 2–5 ms, or until about 32 events are queued, before draining. That adds at most 5 ms latency and cuts wake-ups 10–20×.
- (b) Serialize the whole batch into one pooled buffer (`[len][env][len][env]…`) and issue a single `WriteAsync`. The bytes on the wire stay the same, so the gateway needs no change.
### 2. A timer is created and cancelled on every wait
- `WaitForEventsAsync(EventDrainInterval = 25ms)` calls `SemaphoreSlim.WaitAsync(timeout, ct)` (`MxAccessEventQueue.cs:320`).
- On .NET Framework 4.8, each blocking timed wait allocates a linked `CancellationTokenSource`, a `Task.Delay` timer and a `Task.WhenAny`, then cancels the timer (*inferred*). At ~240 waits/s that is ~240 timer insert/remove pairs per second; a new earliest due time reprograms the native timer, which is a kernel call.
- The 25 ms timeout also wakes an idle worker 40 times/s. The comment at `WorkerPipeSession.cs:17-21` says "an idle worker parks instead of waking 40x/s", which the 25 ms timeout contradicts.
- The STA's outer wait times out every 50 ms (`StaRuntime.cs:32,338`), another 20 wakes/s when idle.
- **Fix:** use an untimed `WaitAsync(ct)` or a timeout of 1 s or more. `RecordFault` already signals the queue, so the short timeout isn't needed for fault discovery. Raise the STA outer wait to 250 ms–1 s too.
### 3. `FlushAsync` on the pipe is pointless
- `WorkerFrameWriter.cs:591,643`.
- On .NET Framework 4.8, `PipeStream.Flush()` only checks state and does not call `FlushFileBuffers`. `PipeStream` does not override `FlushAsync`, so the base `Stream.FlushAsync` runs `Flush` via `Task.Factory.StartNew`: one thread-pool hop per drain pass for no work (*inferred*, from memory of the framework source).
- **Fix:** call `_stream.Flush()` synchronously, or drop the flush. The change is harmless either way.
## Worker: Smaller Per-Event Costs
### 4. Value cache signals on every update
`MxAccessValueCache.cs:127` calls `updateSignal.Set()` (an `AutoResetEvent`) on every data change, even with no waiter. That is a kernel transition of about 0.5–3 µs per event.
**Fix:** keep a volatile waiter count and call `Set()` only when it is non-zero. Waiters increment and then re-check before blocking, so a wake can't be lost.
### 5. Timestamp parsed from text on every data change
`MxAccessEventMapper.ApplySourceTimestamp` and `TryParseSourceTimestamp` (L335–421) run `DateTime.TryParseExact` with `AssumeLocal | AdjustToUniversal` on every event, which converts through `TimeZoneInfo.Local`. Cost is about 3–8 µs.
If the exact format misses, the parse falls back to `DateTime.TryParse` with the current culture and then the invariant culture, costing about 10–30 µs per event. `LmxSubtagAlarmSource.ConvertTimestampUtc` repeats the same pattern, but only when alarms are enabled.
**Fix:** memoise the last string and its parsed result, since many events share a timestamp, or hand-parse the fixed format. Add a counter to confirm the exact parse isn't missing.
### 6. Minor
- `MxStatusProxyConverter.ConvertMany` (L58–83) uses `foreach (object …)` over the status array, which boxes each `MXSTATUS_PROXY`, and builds an intermediate `List` that is enumerated again. Index `MXSTATUS_PROXY[]` directly and add straight into the `RepeatedField`.
- `CalculateSize()` runs on enqueue (`MxAccessEventQueue.cs:~225`, for the drain byte budget) and again on write. Reuse the size.
- `MxAccessBaseEventSink.OnDataChange` (L133–157) creates two closures and delegates per callback, and `ApplySourceTimestamp` allocates a throwaway `MxValue`.
- `StaMessagePump.cs:27` and `StaWaitHelper.cs:85` allocate a new `IntPtr[]` per wait. Cache one per instance.
- Per-event allocations on the drain/write path: `List<WorkerEvent>` (`MxAccessEventQueue.cs:361`), envelope array, `PendingFrame`, the `written` list (`WorkerFrameWriter.cs:572`), and the net48 overlapped I/O objects. Each envelope also repeats `protocol_version` and `session_id`. Finding 1 reduces all of this.
- `VariantConverter` array conversion (`ConvertInt32Array`, `ConvertDoubleArray`) boxes per element via `foreach (object …)` + `Convert.ToXxx`. This only matters if many tags are arrays; add typed fast paths for `int[]`, `double[]`, `float[]`, `bool[]`, `string[]`.
## Gateway Relay
The gateway doesn't push back on the worker:
- The pipe read loop never blocks. `StageWorkerEvent` (`WorkerClient.cs:716`) uses a non-blocking `TryWrite`, and staging overflow faults the session rather than throttling the worker (`WorkerClient.cs:735-748`).
- The production pipe has 128 KiB buffers each way (`SessionWorkerClientFactory.cs:25,171-194`).
- The zero-buffer pipe change in `02baf0c` touched test helpers only.
Possible improvements, none of them urgent:
1. **Batch events per frame.** `WorkerEnvelope` carries one `MxEvent` per frame, and the gateway does two pipe reads per frame (`WorkerFrameReader.cs:41-77`), so about 480 reads/s at 240 events/s. A `WorkerEventBatch { repeated MxEvent }` body would cut reads to roughly one per drain tick and save per-envelope overhead. This is a contract change (`mxaccess_worker.proto` plus a protocol version bump, worker and gateway), so do it after worker fix 1(b).
2. **Per-event metrics.**
- `GatewayMetrics.EventReceived` (`Metrics/GatewayMetrics.cs:253-260`) does two `ConcurrentDictionary.AddOrUpdate` calls per event, hashing the session id and family string. Cache per-session counters (array indexed by family) in `WorkerClient`.
- `MxAccessGatewayService.cs:187-206` records a send-latency histogram on every gRPC write. Sample it, for example 1 in 16.
3. **Replay buffer size walk.** `SessionEventDistributor.cs:959-961` runs `CalculateSize()` on every append (the `ReplayBufferMaxBytes` 64 MiB cap is on by default) and calls `GetUtcNow` twice. Carry the frame length through from the reader, or check the byte cap every N appends.
4. **Idle internal subscribers.** The dashboard mirror (`GatewaySession.cs:942-960`) and the alarm monitor (`GatewayAlarmMonitor.cs:285-305`) wake on every data change only to discard it. Filter at the distributor with a per-subscriber predicate, and attach the mirror lazily when a viewer exists.
5. **Extra async hop.** The staging-to-events-channel hop (`WorkerClient.cs:753-768`) adds a thread-pool hop per event. Drop the staging hop, or drain with `TryRead` in a loop.
## Already Fine
- **COM event to protobuf.** No reflection per event (status field accessors are compiled once and cached), no COM property reads across the RCW, no logging, no `DateTime.Now`, no LINQ, no linear scans (dictionary-keyed caches), no exceptions for control flow.
- **Alarm path.** `LmxSubtagAlarmSource` uses a separate COM server instance, so data changes aren't checked against alarm subtags. Its poll runs every 500 ms and only when alarms are enabled.
- **STA pump.** `MsgWaitForMultipleObjectsEx` with `QS_ALLINPUT` + `MWMO_INPUTAVAILABLE`, draining to empty, so it doesn't spin. No `SpinWait`, `Task.Delay` polling or `timeBeginPeriod` in the repo. Drain continuations never run inline on the STA.
- **Frame writer.** Length prefix and body go out in one write from one pooled buffer. No `ToByteArray`, and no blocking on async.
- **Frame reader.** The worker reader is a single pending read; the gateway reader reuses its prefix buffer, rents the body from `ArrayPool`, and parses with no copy.
- **Gateway fan-out.** The replay ring is a circular array with no per-append allocation or clone. Fan-out uses a copy-on-write subscriber array with no cross-session lock. Dashboard `Publish` bails on `HasViewers` before cloning. No per-event ACL, LDAP, DB, JSON or logging work. OTel tags are by family only.
- **Heartbeat.** Every 5 s, negligible.
## Confirm With a Profile
> **Status (2026-11-21):** step 1 is done; see the [WPR Trace](#wpr-trace-wonder-app-vd03-2026-11-21). Steps 2–4 were not run: the user declined `powercfg /energy`, and the trace made them unnecessary.
1. **Capture a trace.** Take a WPR or PerfView trace of the worker (and gateway) under load, with CPU sampling and context-switch stacks. It splits kernel from user time and shows whether the cost is in our thread-pool and I/O completions (findings 1–3) or inside MXAccess COM marshalling (`OnDataChange(... ref MXSTATUS_PROXY[])` marshals a SAFEARRAY in and out per callback).
2. **Check timer resolution.** Run `powercfg /energy` on the box. If MXAccess or ArchestrA raises the system timer resolution (`timeBeginPeriod(1)`), that raises interrupt and kernel CPU machine-wide.
3. **Count pumped messages.** `PumpPendingMessages` already returns a count that nothing uses. Report it in the heartbeat to see whether the STA handles about 240 messages/s or far more.
4. **Compare against the old build.** The same trace on a worker built from before `f4a6cb1d` is the cleanest comparison. On a production box that requires a deploy.
## Live Capture: wonder-app-vd03 (2026-11-21)
Counters only: one WinRM call running `typeperf`, 30 × 1 s samples. WPR and `powercfg` were skipped to limit security-software exposure, so there are no call stacks yet. vd03 has 4 logical CPUs and runs two workers (PIDs 20376 and 28660, both started 2026-11-19 15:11). Raw data is in the session scratchpad, `vd03-perf/counters.csv`.
| Counter (mean over 30 s) | Hot worker (`#1`) | Other worker |
|---|---|---|
| % User Time (of one core) | 15.7 (max 22) | 0.0 |
| % Privileged Time (of one core) | **28.8** (max 37) | 0.15 |
| Total, as share of the 4-core box | **≈ 11%** | ≈ 0% |
| Busiest thread (instance 4) | **33.9% of a core**, only ~110 context switches/s | idle, ~150 cs/s |
| Other busy threads (instances 22, 26, 27, 29) | ~3,000–7,700 cs/s **each**, 1–3% CPU | 22, 23, 25, 26 ~550 cs/s each **while idle** |
System-wide: ~136k context switches/s and ~12.8k interrupts/s. With 4 cores, an interrupt rate that high suggests the system timer resolution has been raised. Some per-thread peaks in the hundreds of thousands are counter artifacts (thread instance indexes reshuffle as thread-pool threads come and go); they are ignored here.
What this shows:
1. **The 8–12% is reproduced.** One worker uses about 44% of one core, and two thirds of that is kernel time.
2. **Most of it is one thread.** Thread instance 4 burns about a third of a core while switching only ~110 times/s. At 240 events/s, a thread that waited between events would switch at least 240 times/s. So this thread is either processing continuously or making system calls in a loop that rarely blocks. The STA wait loop was ruled out as a spin source:
- the wake event is an `AutoResetEvent`;
- `PumpPendingMessages` drains with `PeekMessage(PM_REMOVE)` until the queue is empty.
If thread 4 is the STA, the cost is inside MXAccess's own work on that thread (COM marshalling of `OnDataChange` and LMX internals), not in our loop. That would be about 1.4 ms of CPU per event.
3. **Several threads wake thousands of times per second, even in the idle worker.** The idle worker's ~550 cs/s per thread is about one wake every 1.8 ms. That looks like polling at a raised 1 ms timer resolution, by MXAccess/ArchestrA's in-process threads or by our thread-pool hops (findings 1–3). In the hot worker, threads 22/26/27/29 run at 3–8k cs/s, about 15–30 switches per event. That is well above the 3–4 hops per event the code review predicted.
Next step: attribute threads 4 and 22–29 to modules. That needs call stacks, so reproduce on windev (no security software, MXAccess installed) and take a WPR CPU + CSwitch trace, or allow a single WPR capture on vd03. Check `powercfg /energy` for timer-resolution requests at the same time.
## WPR Trace: wonder-app-vd03 (2026-11-21)
**Capture.** One `wpr -start CPU -filemode` capture, 10 s, in a single WinRM call.
- The box generates ~136k context switches/s, so the trace came out at 2 GB with ~1.1M events lost. Most of the lost events are CSwitch records; the proportions below are still meaningful.
- A first attempt with `-start DotNET` produced 5 GB and was discarded.
- Analysis used a TraceEvent console tool on windev: source in the session scratchpad `etlan/`, built at `C:\build\perfan\src`. Symbols came from the Microsoft symbol server. ArchestrA modules have no PDBs, so their frames are `module!0xaddr`.
**Where the hot worker (PID 20376) spends its CPU:** 17,256 samples, the most of any process on the box.
| Thread | Samples | Share |
|---|---|---|
| STA thread (TID 28952) | 12,347 | **72%** |
| Six CLR thread-pool workers | ~4,400 | **26%** |
| Everything else | ~500 | 2% |
### Finding A: per-event registry and typelib lookups on the STA (72%)
The STA's samples all sit under one path:
```
StaRuntime.ThreadMain → StaMessagePump.PumpPendingMessages → user32!DispatchMessage
→ lmxproxy (window proc) → lmx (LMX internals) → lmxproxy!0x67f0c1e1
→ oleaut32!GetRecordInfoFromGuids (2,867 / 4,064 hot samples = 70%)
→ LoadRegTypeLib → LoadRegTypeLibOfSzGuid
→ GetTypeLibPathFromRegistry → RegOpenKeyEx (HKCR\TypeLib\…, WOW64-redirected) (1,662 = 41%)
→ remainder: typelib load (file open through fltmgr/ntfs)
↳ every registry op enters ntoskrnl!CmpCallCallBacksEx → csagent.sys (CrowdStrike Falcon) (1,622 = 40%)
```
- **What triggers it.** On every `OnDataChange`, MXAccess's own proxy (`lmxproxy.dll`) builds the `MXSTATUS_PROXY` user-defined-type array that the event carries (`ref MXSTATUS_PROXY[]`). To do that it calls `GetRecordInfoFromGuids`, which resolves the type library through the registry each time.
- **Why it costs so much here.** The worker is x86 under WOW64, so every registry path is rewritten for redirection. CrowdStrike's kernel registry callback then inspects each key open and query. Together they make each event cost about 1.4 ms of STA CPU, and most of it is kernel time. That explains why privileged time was twice user time.
- **Our code isn't the cost.** Our managed code on the STA is negligible. The pump appears only as the frame that dispatches the message.
### Finding B: CLR thread-pool spin-wait (26%)
- **Where the threads wait.** About 170k switch-ins on the six pool threads resume from `kernelbase!SleepEx ← clr!ClrSleepEx ← ThreadpoolMgr::WorkerThreadStart`. This is the .NET Framework thread pool's spin-wait for work (`UnfairSemaphore`), and it repeatedly sleeps and yields.
- **What wakes them.** They are woken by `ThreadpoolMgr::MaybeAddWorkingWorker` (878 managed work requests, 232 unmanaged), which is triggered by:
- the per-event work items: `SemaphoreSlim.Release` continuations, pipe I/O completions and `FlushAsync`'s `StartNew` (findings 1–3);
- our STA thread (tid 28952) and the pipe writer.
- **What it costs.** Each work item makes a worker spin through dozens of sleeps before parking. That gives ~7k context switches/s per thread, about 150 per event, which is far more than the 3–4 hops findings 1–3 estimated.
### What this changes
1. **The biggest cost (A) is inside MXAccess's proxy, amplified by WOW64 and CrowdStrike.** None of the code-review findings touch it. Mitigations, in order of how easy they are to try:
- **Pin the type library.** At worker startup, on the STA, call `LoadRegTypeLib` for the MXAccess type library that defines `MXSTATUS_PROXY`, then call `GetRecordInfoFromGuids`. Hold both for the process lifetime. oleaut32 caches loaded type libraries, so this should remove the load/file-open share (about 28% of STA samples). It will likely not remove the `GetTypeLibPathFromRegistry` registry reads. This needs measuring on windev before relying on it.
- **Ask Security for a CrowdStrike exclusion.** A registry/file-monitoring exclusion for `MxGateway.Worker.exe` (via the security team) would remove csagent's ~40% share. A useful comparison: windev has no CrowdStrike, so the same load there should show the uninflated cost.
- **Check for a non-UDT event path.** Look in the mxaccess analysis project (`docs/MXAccess-Public-API.md`) for an MXAccess interface or event variant that does not marshal the `MXSTATUS_PROXY` array per event.
- **Checked 2026-11-21: there is none.** Every event on both source interfaces (`_ILMXProxyServerEvents`, `_ILMXProxyServerEvents2`), namely `OnDataChange`, `OnWriteComplete`, `OperationComplete` and `OnBufferedDataChange`, takes `ref MXSTATUS_PROXY[] pVars`. The Ghidra notes show `OnBufferedDataChange` is fired from the same native callback and also builds the status SAFEARRAY. Switching event families would not avoid the lookup, so the pin is the fix.
2. **Finding B is ours.** It confirms findings 1–3 and makes them more important.
- The strongest fix is to take event draining off the thread pool. Use a dedicated writer thread that blocks on a kernel event and writes synchronously to the pipe. That avoids pool wake-ups per event entirely.
- The coalescing window (1a) and dropping `FlushAsync` (3) are the cheaper partial fixes.
3. **Other processes on the box switch threads even more.** `MxGateway.Server` (240k context switches in the trace, the most on the box) and `ZB.MOM.WW.ScadaBridge.Host` (229k) both switch more than the worker. That points at the same .NET thread-pool pattern on the gateway side, which was not analysed here.
## Prototype Results: windev (2026-11-21)
Branch `feat/worker-perf-prototype` (committed as `659bb831`), applied to `main` `08a9cfd6`. It makes two changes:
1. **Type-library pin.** `MxStatusProxyRecordInfoPin` (new) calls `LoadRegTypeLib` and `GetRecordInfoFromGuids` once per process for the LMXProxy type library and `MXSTATUS_PROXY`, and holds both references for the process lifetime.
- The GUIDs are read from the interop metadata: library `{77e896ec-b3e3-4de4-b96f-f32570164211}` v3.2 (`MXAccess32.tlb`), record `{A162D9E4-9019-42F3-A087-79264007E542}`.
- It is called from `MxAccessComObjectFactory.Create()`, which runs on the STA before the first `LMXProxyServerClass`.
- It is best-effort: a failure is recorded in `Status` and logged as `WorkerRecordInfoPin`, and never fails the session.
2. **Dedicated drain thread.** `WorkerPipeSession`'s event drain loop runs on a dedicated background thread (`mxgw-event-drain`) instead of as an async thread-pool loop.
- It parks on a new blocking `IWorkerRuntimeSession.WaitForEvents`, which wraps the same coalesced `SemaphoreSlim` used by `WaitForEventsAsync`.
- It returns a `TaskCompletionSource` task, so the message loop's `Task.WhenAny` supervision is unchanged.
- `WorkerFrameWriter` calls `Stream.Flush()` synchronously instead of `FlushAsync`; on .NET Framework, `PipeStream.FlushAsync` costs a `StartNew` hop.
**Tests.** The full worker suite passes on windev: 783 passed, 14 skipped (live-gated). Ten `WorkerFrameProtocolTests` stream doubles were changed from overriding `FlushAsync` to overriding `Flush`.
**Micro-benchmark** of `GetRecordInfoFromGuids` in an x86 process on windev, 20k calls:
| Mode | µs per call | User | Kernel |
|---|---|---|---|
| No pin | 1,037 | 313 | 725 |
| Type library pinned | 682 | 208 | 474 |
| Type library + record info pinned | **0.4** | 0.8 | 0 |
**End-to-end benchmark.** A scratch Release gateway ran on `127.0.0.1:5220` (auth, LDAP, dashboard and alarms off), with the deployed `MxAccessGw` service left untouched.
- The load client `perfload` subscribed to 120 items, which is `TestMachine_001..040.TestChangingInt` ×3, giving ~242 events/s.
- Worker CPU was measured over 40–50 s after a 20 s warm-up, with two runs per variant.
| Worker variant | Worker user | Worker kernel | **Worker total** (% of one core) | Bench gateway CPU |
|---|---|---|---|---|
| Baseline (`main`) | 36.0 | 31.0 | **67.0** | 14.2 |
| Writer thread only | 18.9 | 24.4 | **43.2** | 12.1 |
| Pin only | 7.7 | 2.0 | **9.7** | 7.5 |
| **Both** | 4.9 | 1.3 | **6.2** | 7.7 |
What the results show:
- **The pin is the big lever.** It takes the worker from 67% to 9.7% of a core, about 7×. Kernel time drops 31 → 2.
- **The writer thread is worth about 24 points on its own, and about 3.5 on top of the pin.**
- **Together they cut worker CPU about 11× at the same event rate**, from ~2.8 ms to ~0.26 ms of CPU per event.
- **The bench gateway's CPU also halves once the pin is in.** This is not yet explained; the likely cause is the worker's STA no longer stalling and bunching delivery.
- **The per-thread context-switch counter was unreliable** across these runs (thread-instance churn), so it is not reported.
- **Expect a bigger pin gain on vd03.** windev has no CrowdStrike, which on vd03 added `csagent.sys` registry callbacks to every lookup the pin removes. That is an inference, not yet measured.
**Before productizing** (all done in `30ac3f32`: docs incl. `gateway.md`, the pin outcome in `WorkerReady.record_info_pin_status` shown in the gateway log and dashboard, and cancel/fault drain-thread tests; rollout in `docs/plans/2026-11-21-worker-perf-rollout.md`, gate #236):
- Update `docs/MxAccessWorkerInstanceDesign.md` and `docs/WorkerFrameProtocol.md` (drain thread model, record-info pin) and `gateway.md`'s STA section in the same change.
- Surface `MxStatusProxyRecordInfoPin.Status` somewhere visible. Worker stdout is not captured by the gateway, so the log line is currently unseen; the heartbeat or `WorkerReady` would work.
- Add a unit test for the drain thread's cancel and fault completion paths.
Artefacts on windev:
- `C:\build\perfproto`: worktree with the patch.
- `C:\build\perfbench\worker-{base,proto,pin,writer}`: the worker builds.
- `C:\build\perfbench\bench-run.ps1 -Variant <v> -Seconds 40 -Warmup 20 -Repeat 3`: the benchmark.
- `C:\build\perfbench\perfload`: the load client.
## Gateway Investigation (vd03 trace, 2026-11-21)
This is the analysis of the same vd03 trace for `MxGateway.Server` (PID 8544): 239,603 switch-ins in 10.7 s (~22.4k/s) and ~55% of one core. The analyser is at `C:\build\perfan\src-gw` on windev; the reports are in the session scratchpad as `gw-report.txt` and `gw-attr2.txt`.
- **93% of switches are thread-pool spin yields.** 222.6k switch-ins resume from `SleepEx ← LowLevelLifoSemaphore.Wait ← PortableThreadPool+WorkerThread.WorkerThreadStart`, with wait reason `WrYieldExecution`.
- They come in runs averaging 27 yields. The .NET 10.0.8 spin limit is 70, with a `Sleep(0)` on every other step from step 10, so about 30 `Sleep(0)` calls per idle spell.
- Of the non-ETW CPU on the pool threads, 66% is this spin and 34% is real relay work.
- **Pipe reads.** Each frame costs two I/O-completion wakes, one for the 4-byte prefix and one for the body. About 4% of switches.
- **gRPC writes.** About 0.7%, as `WSASend` preemptions under a CrowdStrike user-mode hook (`umppc21408.dll`).
- **Negligible:** SignalR/dashboard, timers, metrics, `CalculateSize` in the replay buffer, health checks, OTel and Galaxy polling. The code review's per-event metric and replay findings are refuted as material.
Ranked fixes (unmeasured):
1. **Lower the pool's spin limit.** Set `DOTNET_ThreadPool_UnfairSemaphoreSpinLimit=10`, or `System.Threading.ThreadPool.UnfairSemaphoreSpinLimit` in runtimeconfig. That removes the `Sleep(0)` yields, which are about 93% of switches. Apply it as an NSSM env var or a `RuntimeHostConfigurationOption`. ScadaBridge (229k switches on vd03) likely needs the same, which is a cross-repo item.
2. **Remove relay hops.** Each event currently makes about 6 of our pool work items plus 2–3 of Kestrel's, giving ~2.1 spin spells per frame. Three cuts:
- `AllowSynchronousContinuations=true` on `_eventStaging` and `_events`, or run the mapping and fan-out inline on the read loop (`WorkerClient.cs:723,753-768,791`). Saves 2 per event.
- Attach the dashboard mirror (`GatewaySession.cs:656,851`) only while there are viewers. Saves 1.
3. **Buffer the pipe reader** (`WorkerFrameReader.cs:46,72`), with a `PipeReader` or a 64 KiB pooled buffer, to avoid two completions per frame.
4. **Batch gRPC writes.** Use `WriteOptions(WriteFlags.BufferHint)` while `EventStreamService.cs:224` has more events buffered, and flush on the last one. Verify grpc-dotnet's `BufferHint` semantics first.
## Gateway Spin-Limit Benchmark: windev (2026-11-21)
Same harness as the prototype results: prototype worker, ~242 events/s, 120 items, two interleaved rounds. The only change between runs is `DOTNET_ThreadPool_UnfairSemaphoreSpinLimit` on the scratch gateway process, passed with `bench-run.ps1 -GwEnv`.
| Gateway spin limit | Gateway CPU (% of one core), round 1 / 2 | Mean | Gateway context switches/s (median) |
|---|---|---|---|
| Default (70) | 7.90 / 8.25 | **8.1** | 591 / 641 |
| `10` | 7.09 / 6.77 | **6.9** (−15%) | 1,004 / 893 |
| `0` | 6.97 / 6.37 | **6.7** (−18%) | 1,012 / 982 |
The worker was unaffected (6.2–6.8% in every run).
- **A modest win on windev.** The CPU saving is real and consistent: about 1.2–1.4 points of a core, which is 15–18% of the gateway's CPU. `0` is marginally better than `10`.
- **Context switches went up, not down, and that is expected here.** windev is mostly idle, so the pool's `Sleep(0)` yields return without switching. That is why the default shows fewer switches. With spinning cut short, idle workers park on the semaphore and are woken by a real switch each time. On vd03, the 4-CPU box is oversubscribed, so every `Sleep(0)` *did* switch, which produced the 222k yield switches. The limit should remove most of those there.
- **windev therefore under-represents the vd03 gain.** The benefit scales with how busy the box is. That is an inference; confirm it with a counter capture on vd03 after deploying.
- **Recommendation:** ship `DOTNET_ThreadPool_UnfairSemaphoreSpinLimit=10` as a `RuntimeHostConfigurationOption` (`System.Threading.ThreadPool.UnfairSemaphoreSpinLimit`) in the Server csproj, so it travels with the build rather than NSSM config. `10` keeps a short busy-spin for back-to-back work at almost the same CPU as `0`. The relay-hop fixes (gateway fixes 2–3) remain the structural cure: they cut the number of wakes rather than the cost of each.
## vd03 Capture Log (2026-11-21)
WinRM diagnostics are outside the `winrm` skill's deploy-only scope. They were used here as a one-off exception the user approved. The user declined `powercfg /energy`.
| # | WinRM call | Result |
|---|---|---|
| 1 | `typeperf` counter capture | Failed: no process `ZB.MOM.WW.MxGateway.Worker`. vd03's exe is renamed `MxGateway.Worker.exe`. |
| 2 | Same capture, process name `MxGateway.Worker` | 30 × 1 s counter samples. |
| 3 | `wpr -start CPU -start DotNET -filemode`, 20 s, plus per-thread TID map | 5 GB ETL, 1.35M events lost. Discarded; only the TID map CSVs were kept. |
| 4 | `wpr -start CPU -filemode`, 10 s | 2 GB ETL, 1.1M events lost. Used for analysis. |
- Files were pulled and deleted over SMB (`winrm smb pull` / `smb rm`). Both `E:\psrem-stage\perf-*` folders are gone from vd03.
- The 2 GB pull took about 19 minutes (~1.7 MB/s). Copying it on to windev took about 1 minute.
- **For a repeat run:** use `-start CPU` only, keep it to ≤10 s, and never use `-start DotNET`.
- The analyser (TraceEvent, .NET 10) is at `C:\build\perfan\src` on windev, and the trace at `C:\build\perfan\worker.etl`. Run it with `dotnet bin\Release\net10.0\etlan.dll <etl> <pid> <hotTid>`.
## Suggested Order
Revised after the windev prototype and the gateway trace analysis:
1. **Productize the worker prototype** (`feat/worker-perf-prototype`): the type-library pin plus the dedicated drain thread, with the docs, status surfacing and tests listed above. Measured on windev: worker CPU 67% → 6% of a core at ~240 events/s.
2. **Deploy to vd03 and re-measure** with the same counter capture. Expect a larger gain there than on windev, because of CrowdStrike.
3. **Gateway: lower the pool spin limit** (`System.Threading.ThreadPool.UnfairSemaphoreSpinLimit=10` in the Server csproj). Measured on windev: gateway CPU −15%; the gain should be larger on the busier vd03. Raise the same setting as a cross-repo item for ScadaBridge.
4. **Gateway: remove relay hops** (`AllowSynchronousContinuations`, a lazy dashboard mirror) and buffer the pipe reader.
5. **Ask Security for a CrowdStrike exclusion** for `MxGateway.Worker.exe`, only if vd03 still shows `csagent` cost after step 2.
6. **Remaining code-review items:** finding 4 (value-cache `Set`), finding 5 (timestamp memoisation), the coalescing window, and gRPC `BufferHint`. Then the `WorkerEventBatch` protocol change, only if per-frame cost still shows.