204 lines
18 KiB
Markdown
204 lines
18 KiB
Markdown
# Server Workers / Metrics / Diagnostics: Bugs and Performance Review
|
|
|
|
- **Date:** 2026-12-02
|
|
- **HEAD:** 54367e74
|
|
- **Scope:** `src/ZB.MOM.WW.MxGateway.Server/Workers/`, `Metrics/`, `Diagnostics/`, plus `Sessions/SessionWorkerClientFactory.cs` (the pipe server) where it completes a worker-launch finding.
|
|
- **Method:** read-only source review. Nothing was built or run; every finding is from reading the cited code. "Confirmed" means the code path is unambiguous; "Plausible" means the path exists but the trigger depends on timing or environment that was not reproduced.
|
|
|
|
Paths below are relative to `src/ZB.MOM.WW.MxGateway.Server/`.
|
|
|
|
## Summary
|
|
|
|
| ID | Severity | Category | Confidence | Title |
|
|
|---|---|---|---|---|
|
|
| WRK-001 | Medium | Bug | Confirmed | Command timeouts keep resetting the heartbeat stuck-ceiling, so a hung worker under steady command traffic is never faulted |
|
|
| WRK-002 | Medium | Bug | Confirmed | Pipe-connect wait does not observe worker exit; a worker that dies at startup costs the full `StartupTimeout` and reports a bare timeout |
|
|
| WRK-003 | Low | Bug | Plausible | Command timeout does not cover the outbound enqueue; a stalled write loop blocks `InvokeAsync` past its deadline |
|
|
| WRK-004 | Low | Bug | Confirmed | Timeout arm throws `CommandTimeout` even when the reply won the race and was counted as a success |
|
|
| WRK-005 | Low | Bug | Plausible | Heartbeat staleness is measured on the wall clock; a forward clock step faults every idle session |
|
|
| WRK-006 | Low | Bug | Plausible | A throwing `Kill` in launch-failure cleanup masks the original error and skips the pipe dispose |
|
|
| WRK-007 | Low | Bug | Confirmed | Commands that fail before the reply wait increment `commands.started` but no terminal counter |
|
|
| WRK-008 | Low | Bug | Plausible | `EventReceived` can re-create a session's `_eventsBySession` entry after `RemoveSessionEvents`, leaking it |
|
|
| WRK-009 | Low | Bug | Plausible | Orphan cleanup has no ownership check; it kills live workers of another gateway instance and any same-named process whose path is unreadable |
|
|
| WRK-010 | Low | Performance | Confirmed | Each command envelope is size-walked an extra full pass for the `CommandTooLarge` pre-check |
|
|
|
|
No Critical or High findings. The frame reader and writer (`WorkerFrameReader.cs`, `WorkerFrameWriter.cs`) were checked for partial reads, length validation, max-size enforcement, pooled-buffer aliasing and cancellation mid-frame, and no defect was found. The fault/close/dispose ordering in `WorkerClient` (terminal state first, then cancel, then channel completion, then pending-command completion) was traced for correlation leaks and none was found: every path that removes a pending entry releases its slot exactly once.
|
|
|
|
## Known items from `perf.md` still present in code
|
|
|
|
These are not re-reported as findings. They are unchanged at HEAD:
|
|
|
|
- Two pipe reads per frame, unbuffered: `Workers/WorkerFrameReader.cs:46,73`.
|
|
- Staging hop and `AllowSynchronousContinuations = false` on all three channels: `Workers/WorkerClient.cs:94,108,121,753-766`.
|
|
- Per-event `EventReceived` with two `ConcurrentDictionary.AddOrUpdate` calls: `Workers/WorkerClient.cs:720`, `Metrics/GatewayMetrics.cs:253-262`.
|
|
|
|
---
|
|
|
|
## WRK-001: Command timeouts keep resetting the heartbeat stuck-ceiling
|
|
|
|
- **Severity:** Medium
|
|
- **Category:** Bug
|
|
- **Confidence:** Confirmed (logic); the hung-worker trigger was not reproduced
|
|
- **Location:** `Workers/WorkerClient.cs:610-619` (watchdog skip), `:641-660` (`TryGetOldestPendingCommandAge`), `:291-295` (timeout removes the pending entry); defaults at `Workers/WorkerClientOptions.cs:23` (ceiling 75 s) and `Configuration/SessionOptions.cs:8` (command timeout 30 s)
|
|
|
|
**Description.** When the heartbeat is stale, the watchdog skips the fault while the oldest entry in `_pendingCommands` is no older than `HeartbeatStuckCeiling`. The intent is "one slow COM call may hide the worker for at most 75 s". But a command that hits its own timeout is removed from `_pendingCommands`, so the "oldest pending command" is only ever as old as the command timeout. With the defaults (30 s timeout, 75 s ceiling) no entry can reach the ceiling. The suppression is therefore bounded by command age, not by how long the heartbeat has been missing.
|
|
|
|
**Failure scenario.** The worker process stops responding entirely (suspended, deadlocked pipe writer, hung outside the STA) so it sends no heartbeats and no replies. A client polls the session, for example a read every few seconds, retrying after each `DeadlineExceeded`. At every 5 s watchdog tick there is at least one pending command younger than 30 s, so the check at line 615 always continues. The session stays `Ready` indefinitely, events have silently stopped, and the client only sees per-call timeouts and is never told to reopen. A session with no command traffic is faulted after 15 s, so active clients get worse detection than idle ones. The 128 KiB pipe buffer means the write loop does not stall for a long time under small commands, so nothing else trips.
|
|
|
|
**Suggested fix.** Bound the suppression by heartbeat age: fault when `now - lastHeartbeatAt > HeartbeatStuckCeiling` regardless of pending commands, and keep the pending-command skip only for the window between `HeartbeatGrace` and the ceiling.
|
|
|
|
**Test idea.** With a `FakeTimeProvider`, stop heartbeats, then issue overlapping `InvokeAsync` calls with a 30 s timeout so one is always pending. Advance past 75 s and assert the client reaches `Faulted` with `HeartbeatExpired`.
|
|
|
|
---
|
|
|
|
## WRK-002: Pipe-connect wait does not observe worker exit
|
|
|
|
- **Severity:** Medium
|
|
- **Category:** Bug
|
|
- **Confidence:** Confirmed
|
|
- **Location:** `Sessions/SessionWorkerClientFactory.cs:66,203` (wait bounded only by `StartupTimeout`), `Workers/WorkerProcessStartedProbe.cs:11-18` (single `HasExited` check immediately after `Process.Start`), `Configuration/WorkerOptions.cs:16` (30 s default)
|
|
|
|
**Description.** The default startup probe checks `HasExited` once, microseconds after the process is created, which is almost always false. After that, `WaitForConnectionAsync` waits only on the startup-timeout token. Nothing races the wait against `process.WaitForExitAsync`. `docs/WorkerProcessLauncher.md` says the probe "only verifies that the worker did not exit immediately" and that the worker client takes over, but the client does not exist until the pipe has connected.
|
|
|
|
**Failure scenario.** The worker exits before connecting to the pipe: a missing .NET Framework dependency, a bad argument, security software terminating it, or an unhandled exception in startup. `OpenSession` holds a session slot for the full 30 s and then fails with `TimeoutException` ("did not complete startup"), with no exit code. Internal reopen loops (the alarm monitor and the dashboard live-data session both open sessions) each pay 30 s per attempt, and the operator sees a timeout rather than a crash.
|
|
|
|
**Suggested fix.** In `CreateAsync`, race `WaitForConnectionAsync` against `processHandle.Process.WaitForExitAsync` and fail fast with a `WorkerProcessLaunchException(StartupFailed)` carrying the exit code. Apply the same race to the handshake reads, or rely on the pipe EOF there.
|
|
|
|
**Test idea.** Use a fake `IWorkerProcess` whose `WaitForExitAsync` completes after 50 ms with exit code 3 and never connects the pipe. Assert `CreateAsync` fails well inside `StartupTimeout` and the message carries the exit code.
|
|
|
|
---
|
|
|
|
## WRK-003: Command timeout does not cover the outbound enqueue
|
|
|
|
- **Severity:** Low
|
|
- **Category:** Bug
|
|
- **Confidence:** Plausible
|
|
- **Location:** `Workers/WorkerClient.cs:270` (enqueue on the caller's token only), `:286` (timeout applied only to the reply wait), `:88-95` (bounded channel, capacity `MaxPendingCommands + 4`), `:959` (cancel envelopes also consume capacity)
|
|
|
|
**Description.** `InvokeAsync` applies `timeout` only to `pendingCommand.Task.WaitAsync`. The preceding `EnqueueAsync` waits on the bounded `_outboundEnvelopes` channel with only the caller's token. A timed-out command frees its pending slot but leaves its envelope in the channel, and adds a `WorkerCancel` envelope. If the write loop is parked in a pipe write, roughly 66 timed-out commands fill the channel. `ShutdownAsync` documents the same stalled-writer condition (lines 398-409) and bounds its own enqueue for that reason; `InvokeAsync` does not.
|
|
|
|
**Failure scenario.** The worker stops reading the pipe but keeps sending heartbeats. Once the pipe buffer and the channel are full, each new `InvokeAsync` blocks in `EnqueueAsync` holding a pending slot. A caller without a gRPC deadline waits indefinitely instead of getting `CommandTimeout` after 30 s. If heartbeats have also stopped, the blocked callers' ageing entries do trip the watchdog after 75 s, so the hang is bounded in that case.
|
|
|
|
**Suggested fix.** Run the enqueue under the same deadline as the reply wait (one linked CTS with `CancelAfter(timeout)`, or `WriteAsync(...).AsTask().WaitAsync(timeout, ct)`), mapping expiry to `CommandTimeout`.
|
|
|
|
**Test idea.** Use a stream whose `WriteAsync` never completes, issue enough commands to fill the channel, then assert a further `InvokeAsync` with `CancellationToken.None` fails with `CommandTimeout` after the timeout.
|
|
|
|
---
|
|
|
|
## WRK-004: Timeout arm throws even when the reply won the race
|
|
|
|
- **Severity:** Low
|
|
- **Category:** Bug
|
|
- **Confidence:** Confirmed
|
|
- **Location:** `Workers/WorkerClient.cs:288-315`
|
|
|
|
**Description.** When `WaitAsync` raises `TimeoutException`, the code calls `RemovePendingCommandAsFailed`. If that returns `false`, the read loop has already removed the entry in `CompleteCommand`, recorded `CommandSucceeded`, and set the result. The comment at lines 300-302 says "the caller is about to see it", but the code then unconditionally throws `CommandTimeout`. The reply is discarded.
|
|
|
|
**Failure scenario.** A `Write` reply arrives within microseconds of the 30 s deadline. The worker performed the write, the gateway counts a succeeded command, and the client receives `DeadlineExceeded` and retries the write. Metrics and client outcome disagree.
|
|
|
|
**Suggested fix.** When `removed` is `false`, `return await pendingCommand.Task` (it is completed or about to be, with the reply or the fault that removed it) instead of throwing the timeout.
|
|
|
|
**Test idea.** With a `FakeTimeProvider`, complete the reply from a hook placed between the timer firing and `RemovePendingCommandAsFailed` (or loop the race), and assert `InvokeAsync` returns the reply whenever `CommandSucceeded` was recorded.
|
|
|
|
---
|
|
|
|
## WRK-005: Heartbeat staleness is measured on the wall clock
|
|
|
|
- **Severity:** Low
|
|
- **Category:** Bug
|
|
- **Confidence:** Plausible
|
|
- **Location:** `Workers/WorkerClient.cs:608-613` (`now - lastHeartbeatAt` using `GetUtcNow`), `:1069,1085` (stamps)
|
|
|
|
**Description.** Both the stamp and the comparison use `TimeProvider.GetUtcNow()`. Pending-command ages already use the monotonic `GetTimestamp`/`GetElapsedTime`; the heartbeat age does not.
|
|
|
|
**Failure scenario.** The host clock steps forward by more than `HeartbeatGrace` (15 s): a time-sync correction after a VM snapshot restore or a domain resync. On the next check tick every `Ready` session with no pending command is declared `HeartbeatExpired` and its worker is killed, all at once. A backward step delays detection of a dead worker by the step size.
|
|
|
|
**Suggested fix.** Keep a monotonic `_lastHeartbeatTimestamp` (`GetTimestamp`) for the watchdog and retain the `DateTimeOffset` only for display.
|
|
|
|
**Test idea.** Use a time provider whose `GetUtcNow` jumps 60 s while `GetTimestamp` advances 1 s; assert no fault.
|
|
|
|
---
|
|
|
|
## WRK-006: A throwing `Kill` in launch-failure cleanup masks the original error
|
|
|
|
- **Severity:** Low
|
|
- **Category:** Bug
|
|
- **Confidence:** Plausible
|
|
- **Location:** `Workers/WorkerProcessLauncher.cs:296-310` (called from the catch blocks at `:149-174`), `Sessions/SessionWorkerClientFactory.cs:129-145`
|
|
|
|
**Description.** Both cleanup paths call `Process.Kill(entireProcessTree: true)` inside a `try/finally` with no catch. `Kill` can throw `Win32Exception` (process is mid-termination or access is denied) or `AggregateException` (a descendant could not be terminated). In the launcher, that exception replaces the `WorkerProcessLaunchException` the catch block was about to throw. In the factory, it replaces the original startup exception and also skips `pipe?.Dispose()` at line 145, leaking the named-pipe server handle. `WorkerClient.KillOwnedProcess` (`Workers/WorkerClient.cs:1202-1217`) already catches and logs for this reason.
|
|
|
|
**Failure scenario.** The worker crashes during startup at the moment the startup timeout fires. `HasExited` returns false, `Kill` throws because the process is terminating, and the caller receives a `Win32Exception` instead of `StartupTimeout`. Error mapping that depends on the launch error code no longer applies.
|
|
|
|
**Suggested fix.** Catch and log in both cleanup paths, and dispose the pipe in a `finally`.
|
|
|
|
**Test idea.** Fake `IWorkerProcess` whose `Kill` throws; assert `LaunchAsync` still throws `WorkerProcessLaunchException` with the original code, and that the factory disposes the pipe.
|
|
|
|
---
|
|
|
|
## WRK-007: Early command failures increment `commands.started` but no terminal counter
|
|
|
|
- **Severity:** Low
|
|
- **Category:** Bug
|
|
- **Confidence:** Confirmed
|
|
- **Location:** `Workers/WorkerClient.cs:236` (`CommandStarted`), `:261-270` (`CommandTooLarge` throw and enqueue), `:335-343` (outer catch releases the slot with no metric); `Metrics/GatewayMetrics.cs:207,237`
|
|
|
|
**Description.** `CommandStarted` is recorded before the try block. Three exits go through the outer catch, which removes the entry and releases the slot but records neither `CommandFailed` nor a latency sample: the `CommandTooLarge` rejection, an `EnqueueAsync` failure (`WriteFailed` on a closed channel), and caller cancellation during the enqueue.
|
|
|
|
**Failure scenario.** A client repeatedly sends oversized bulk writes. `mxgateway.commands.started` climbs while `succeeded + failed` does not, `CommandFailuresByMethod` on the dashboard shows nothing, and the rejections are invisible in metrics.
|
|
|
|
**Suggested fix.** In the outer catch, when `TryRemove` succeeds, record `CommandFailed` with the error code (or exception type) and elapsed time.
|
|
|
|
**Test idea.** Invoke an oversized command with a `MeterListener` attached; assert one `commands.failed` measurement with category `CommandTooLarge`.
|
|
|
|
---
|
|
|
|
## WRK-008: `EventReceived` can re-create a removed session's metrics entry
|
|
|
|
- **Severity:** Low
|
|
- **Category:** Bug
|
|
- **Confidence:** Plausible
|
|
- **Location:** `Sessions/SessionManager.cs:700-702` (`RemoveSessionEvents` before the session and its worker client are disposed), `Workers/WorkerClient.cs:718-721`, `Metrics/GatewayMetrics.cs:257,322`
|
|
|
|
**Description.** `RemoveSessionAsync` drops the per-session event counter and only then disposes the session. On the kill path (`Kill` → `SetFaulted`) the read loop is cancelled but not awaited, so it can still be inside `DispatchEnvelope` for a frame it already read. `StageWorkerEvent` calls `EventReceived` before it checks the terminal state, and `AddOrUpdate` re-creates the entry. Nothing removes it afterwards.
|
|
|
|
**Failure scenario.** A dashboard kill or shutdown-kill of a session that is streaming events. One read-loop iteration lands after `RemoveSessionEvents`. The session id stays in `_eventsBySession` for the life of the process, is copied into every `GetSnapshot`, and is shown as a session with events on the dashboard. Growth is one small entry per affected session.
|
|
|
|
**Suggested fix.** Call `RemoveSessionEvents` after `removedSession.DisposeAsync()` (dispose waits for the read loop), or skip `EventReceived` when the client is terminal.
|
|
|
|
**Test idea.** Hard to hit deterministically; a unit test can call `RemoveSessionEvents` then `EventReceived` and assert the intended contract once a tombstone or ordering fix exists.
|
|
|
|
---
|
|
|
|
## WRK-009: Orphan cleanup has no ownership check
|
|
|
|
- **Severity:** Low
|
|
- **Category:** Bug
|
|
- **Confidence:** Plausible
|
|
- **Location:** `Workers/OrphanWorkerTerminator.cs:56-72,97-112`, `Workers/SystemRunningProcessInspector.cs:40-54`
|
|
|
|
**Description.** At startup every process with the worker image name is killed if its path equals the configured path, or if its path could not be read at all (line 111 returns `true`). There is no check that the process belonged to a gateway that is no longer running. The pipe name on the worker's command line carries the owning gateway PID (`mxgw-{gatewayPid}-{sessionUid}`), but it is not consulted. `MainModule` can also throw transiently for a process that is still starting or already exiting, which is mapped to a null path and so to "orphan".
|
|
|
|
**Failure scenario.** Two gateway processes run from the same build or publish output on one host, for example a developer `dotnet run` alongside an integration-test gateway on windev. Starting the second kills every live worker of the first, and those sessions fault with `PipeDisconnected`. Separately, a same-named worker from a different path (a CI build) is killed if its module read fails during the scan.
|
|
|
|
**Suggested fix.** Read the candidate's command line, parse the gateway PID from `--pipe-name`, and skip the process when that PID is alive and is a gateway. Treat an unreadable path as "skip" unless the command line confirms it.
|
|
|
|
**Test idea.** Extend the fake `IRunningProcessInspector` to return a command line; assert a worker whose owning gateway PID is alive is not killed.
|
|
|
|
---
|
|
|
|
## WRK-010: Extra full size walk per command for the `CommandTooLarge` pre-check
|
|
|
|
- **Severity:** Low
|
|
- **Category:** Performance
|
|
- **Confidence:** Confirmed
|
|
- **Location:** `Workers/WorkerClient.cs:259`, `Workers/WorkerFrameWriter.cs:42,67`
|
|
|
|
**Description.** `InvokeAsync` calls `commandEnvelope.CalculateSize()` for the pre-check, then `WorkerFrameWriter.WriteAsync` calls it again, and `WriteTo` recomputes nested message sizes while serializing. C# protobuf does not cache sizes, so each call walks the whole graph. The comment at lines 248-258 explains why the pre-check size cannot be passed to the writer as the frame length (the sequence stamp changes it), but the walk itself is still repeated.
|
|
|
|
**Failure scenario.** Bulk commands with thousands of items (`WriteBulk`, `AddItemBulk`) pay one extra full traversal of the request graph on the caller's thread per call. It is negligible for single-item commands and is not on the event path.
|
|
|
|
**Suggested fix.** Skip the pre-check walk when a cheap upper bound proves the envelope fits (for example the inbound gRPC request size, already capped below the frame maximum by `EnvelopeOverheadReserveBytes`), or have the writer accept the pre-stamp size and add the exact encoded size of the sequence field.
|
|
|
|
**Test idea.** A micro-benchmark of `InvokeAsync` with a 10,000-item bulk write, before and after.
|