docs(review): 2026-12-02 bug + performance review (99 findings) and fix plan

This commit is contained in:
Joseph Doherty
2026-12-02 16:06:56 -05:00
parent 54367e7408
commit f200bda605
10 changed files with 2013 additions and 0 deletions
+146
View File
@@ -0,0 +1,146 @@
# Fix Plan — 2026-12-02 Bug and Performance Review
Plan for the 99 findings in [README.md](README.md). The work is grouped into phases by risk: security and authz first, then merging the perf work that already exists, then lifecycle, alarms, conversion, the remaining performance items and the clients. Each phase is one branch (`fix/review-2026-12-<phase>`) and can merge on its own. Phases 0–2 come first. Phases 3–6 are independent of each other and can run in parallel.
Per CLAUDE.md, file each phase (or each High finding) as a Gitea issue labelled `type:review-finding` plus a priority, and refer to issues as `#N`. Docs change in the same commit as the code. During each task run only the targeted tests (`--filter`), and run the full gateway suite once at the end of the phase.
---
## Phase 0 — Authorization and auth throttling (p0)
These are real trust-boundary gaps. The SES-002, SES-003 and DSH-001 code paths were re-checked by hand.
| # | Finding(s) | Change | Test |
|---|---|---|---|
| 0.1 | SES-002 | Add an `EnsureOwner(session, identity)` helper next to `ResolveSession` in `Grpc/MxAccessGatewayService.cs` and call it from `Invoke` and `CloseSession`, returning `PermissionDenied` (same ordinal compare as `EventStreamService.cs:58`). Decide whether an `admin`-scoped key may override, and record that in `docs/Authorization.md` and `docs/DesignDecisions.md`. Internal `ISessionManager` callers (alarm monitor, dashboard) are unaffected. | Key B → `Invoke(DrainEvents/Write)` and `CloseSession` on key A's session gives `PermissionDenied`, and A's session stays `Ready`. |
| 0.2 | SES-003 | Add an `AddBufferedItem` case to `ApplyConstraintsAsync` that calls `EnforceReadTagAsync(command.AddBufferedItem.ItemDefinition)`. Also make the switch fail closed: maintain an explicit allow-list of command kinds that carry no tag, and send any new tag-bearing kind to the check (a test enumerates `MxCommandKind`). | Out-of-scope `AddBufferedItem` gives `PermissionDenied` plus an audited denial, and no worker command is sent. Enum-coverage test. |
| 0.3 | DSH-001 | Replace `RouteView` with `AuthorizeRouteView` (with `NotAuthorized` content) in `Dashboard/Components/Routes.razor`. Check `/admin/secrets` (Secrets.Ui) under the same path. | bUnit or integration test: anonymous-localhost principal navigating in-circuit to `/alarms` gets NotAuthorized. |
| 0.4 | SEC-001 | Partition the failure limiter on the remote IP only (strip the port from `context.Peer`, or use `HttpContext.Connection.RemoteIpAddress`). | Two connections from the same IP with different ports share one partition. |
| 0.5 | SEC-002, SEC-003 | Move a valid-secret cache hit ahead of the aggregate throttle, so a holder of the correct secret is never denied by spray against the key id. Stop the success path from wiping the cross-peer aggregate; let entries decay by window instead. | Spray with bad secrets for key X, then the valid secret for X still succeeds. An active key still accrues aggregate failures. |
| 0.6 | SEC-004, DSH-006 | Key revocation or deletion cancels that key's open server streams: register stream CTSs by key id, and the revoke path cancels them. For the dashboard, re-validate the hub-token / cookie expiry and the role on a timer per hub connection and circuit, and abort when expired. | Revoke a key mid-`StreamEvents` and the stream ends with `Unauthenticated`. Hub connection is closed after the token expires. |
**Verify:** `dotnet build src/ZB.MOM.WW.MxGateway.NonWindows.slnx`; filtered tests `MxAccessGatewayService*`, `GatewayGrpcScope*`, `*FailureLimiter*`, `Dashboard*Authorization*`; full gateway suite once.
---
## Phase 1 — Land the existing perf work (p1)
MXA-002 / WIP-002 / MXA-006. The fixes are already written, tested on windev, and deployed on DEV vd03 (worker CPU 45% → 0.3% of a core). They were never merged. The branches stack:
```
main ── feat/worker-perf-prototype (+3, #236) ── feat/gateway-relay-hops (+7, #235) ── fix/readbulk-subscription-teardown (+8, #238)
```
1. Rebase `fix/readbulk-subscription-teardown` onto `main` (each branch is 2 commits behind). It carries all three.
2. Run the windev worker CI (`windev-worker-ci.ps1 -Sha <sha> -Mode test`) and the gateway suite.
3. Merge to `main`, then follow the rollout plan committed on the branch (`3be20983`) for QA and PROD.
4. Then re-assess **WIP-001** (pump drain starving the STA). The record-info pin raises the ~700 ev/s ceiling a lot, but the drain is still unbounded. Cap `PeekMessage` dispatches per loop iteration (for example 64), then service the work queue and stamp activity. Test: a fake message flood with a queued command; the command runs and no `StaHung` fires.
Close `perf.md` by moving it into `docs/` (or deleting it, since it is untracked) once the work is merged.
---
## Phase 2 — Session and worker lifecycle (p1)
| # | Finding(s) | Change |
|---|---|---|
| 2.1 | SES-001 | Close sessions gracefully before Kestrel's stream drain. Do it in an `IHostApplicationLifetime.ApplicationStopping` callback (or a hosted service registered to stop first): close all sessions (workers shut down cleanly), which completes the open `StreamEvents`. Keep the kill as a fallback after a bounded grace. |
| 2.2 | DSH-002, DSH-007 | The dashboard live read closes its session in `finally` (or on any non-faulting failure). Track advised tags before awaiting, so a cancelled subscribe can still unadvise. |
| 2.3 | SES-004 | Lease expiry must not close a session that is detached but still inside `DetachGraceSeconds`. Take the later of the two deadlines, or renew the lease while the stream is attached. |
| 2.4 | SES-005 (+ client keepalive in Phase 6) | Configure Kestrel HTTP/2 keepalive (`Http2.KeepAlivePingDelay/Timeout`) under `MxGateway:*` with defaults, validate it in `GatewayOptionsValidator`, and document it in `docs/GatewayConfiguration.md`. |
| 2.5 | WRK-001, WRK-004 | Command timeouts must not reset the heartbeat stuck-ceiling; track the last real worker reply separately. In the timeout arm, check whether the reply already completed before throwing. |
| 2.6 | WRK-002, WRK-006 | The pipe-connect wait races `Process.WaitForExitAsync`. On early exit, report the exit code and stderr tail. Launch-failure cleanup wraps `Kill` in try/catch and always disposes the pipe. |
| 2.7 | WRK-003 | Include the outbound enqueue in the command deadline. |
| 2.8 | WRK-005 | Use `TimeProvider` / `Stopwatch` monotonic time for heartbeat staleness. |
| 2.9 | WRK-008, SES-007 | Guard `EventReceived` against re-creating a removed session entry (check a removed flag, or remove under the same lock). `Unregister` purges the session's item registrations. |
| 2.10 | WRK-009 | Orphan cleanup kills only workers whose command line or pipe name carries a gateway PID that is no longer alive. |
| 2.11 | MXA-003, WIP-007, WIP-009 | Cover the alarm poll join and handler dispose with the shutdown timeout. The watchdog ignores `ShuttingDown`. Keep a pipe read outstanding, or a parent-PID check, during MXAccess startup, and put a timeout on the hello read. |
**Verify:** gateway build + `Session*`, `WorkerClient*`, `GatewayEndToEndFakeWorkerSmokeTests`. Worker items (2.11) also need the windev x86 build and Worker.Tests.
---
## Phase 3 — Alarm pipeline correctness (p1)
| # | Finding(s) | Change |
|---|---|---|
| 3.1 | MXA-001 | When subscription fails, `PollOnce` reports a failure (it is not a no-op) and does not reset the failure counter. Failover then engages, and "recovered" is reported only after a successful poll. |
| 3.2 | SEC-005, DSH-005 | On monitor restart, emit a provider-status frame and Clear frames for every cached alarm that is absent from the new snapshot (diff, don't drop). New `/hubs/alarms` connections get the current active snapshot and provider status on connect. |
| 3.3 | SEC-006, SEC-009 | Version reconcile snapshots: ignore a snapshot older than the last applied live transition, detect a same-state re-raise by timestamp/sequence, and log or metric a non-OK reconcile reply. |
| 3.4 | SEC-007 | An ack for an alarm not in the cache updates history only; it does not insert an `ActiveAcked` row. |
| 3.5 | MXA-005, MXA-007 | Subtag fallback ignores bad or null-quality `InAlarm` updates (it holds state and marks the provider degraded). Buffer an early `Acked` until `InAlarm` arrives at initial sync. |
| 3.6 | SEC-008, SEC-010 | Cache the watch-list query and fingerprint, refreshing on an interval or a deploy event, not every reconcile tick, and move it out of the failover event loop. Restart backoff becomes exponential with a cap. |
| 3.7 | SEC-011 | Validate `Alarms:ReconcileIntervalSeconds` (> 0) and put an upper bound on `Events:ReplayRetentionSeconds`. |
| 3.8 | SEC-013 | Constraint JSON deserialization turns a missing list member into an empty list (not `null`); add a load-time check so a `null` browse scope can't fall through. |
**Verify:** `GatewayAlarmMonitor*`, `AlarmsHub*`, and Worker.Tests alarm classes on windev. Live check of failover (3.1) and subtag quality (3.5) on the dev rig; the rig's alarms are driven by object logic, so use its simulator.
---
## Phase 4 — Worker value conversion and status mapping (p2)
All worker-side (net48 x86, so no init-only props or records). MXAccess parity is the reference.
| # | Finding(s) | Change |
|---|---|---|
| 4.1 | WIP-003 | Time-typed array and FILETIME conversion catches per element and maps a bad element to a per-item conversion error. One bad value must not fault the session. |
| 4.2 | WIP-004 | Widen integer array elements the same way as the scalar path (`uint` → `int64`). |
| 4.3 | WIP-005 | Worker-side validation failures get a distinct status (not `MxaccessFailure` with `0x80070057`). Check the client error mapping in all five clients. |
| 4.4 | WIP-006 | Apply the #228 local-time fix to time-typed values, not just the timestamp argument. Confirm live before and after on windev. |
| 4.5 | WIP-008 | Null array elements map to an explicit null/empty representation, not 0 / `false` / epoch. Decide against observed MXAccess behaviour first. |
| 4.6 | MXA-004 | Ignore callbacks for removed handles: check the registry before re-creating cache entries. |
**Verify:** windev `windev-worker-ci.ps1 -Mode test`; add conversion unit tests per shape.
---
## Phase 5 — Remaining performance (p2/p3)
| # | Finding(s) | Change |
|---|---|---|
| 5.1 | DSH-003 | The snapshot tick reads cached health results; health checks run on their own cadence. |
| 5.2 | DSH-004, DSH-008, DSH-010 | Coalesce session-details renders (for example 250 ms) and key the rows. `NativeDialog` interop runs only when the open state changes. The Alarms page re-projects only on change. |
| 5.3 | DSH-009 | `AlarmsHubPublisher` skips work when no hub clients are connected. |
| 5.4 | MXA-008, MXA-011 | wnwrap poll skips re-parse when the XML is unchanged (compare hash or length). The alarm poll loop does not wake the STA when there is no alarm subscription. |
| 5.5 | MXA-009 | Completion waits use the intended 50 ms tick and a pending-set, not a full rescan. |
| 5.6 | MXA-010 | Unregister without per-item teardown when the whole server handle goes. Watch-list updates diff the standby instead of rebuilding it. |
| 5.7 | WIP-010 | Move console logging out of the dispatcher gate. |
| 5.8 | WRK-010, WRK-007 | Reuse the computed envelope size for the `CommandTooLarge` check. Pre-reply failures increment a terminal counter. |
| 5.9 | SEC-012, SEC-014 | Trim auth cache-hit allocations (stackalloc hash buffer, cached identity). Audit sweep uses an indexed timestamp predicate and runs off the startup path. |
| 5.10 | SES-006, SES-008 | Reject (or clamp, with a gap sentinel) a resume cursor ahead of the stream. Size-check sparse `Time` array writes before allocating. |
**Verify:** targeted tests per item; for the dashboard items, a manual run with the macOS dashboard rig.
---
## Phase 6 — Clients (p2)
Each item is applied to every affected client in one change, so the five clients stay in step. Run each client's verification from the CLAUDE.md table.
| # | Finding(s) | Change |
|---|---|---|
| 6.1 | CDN-004, CGO-001, CRS-001, CJV-003, CPY-002 | Default HTTP/2 keepalive (for example 30 s ping, 10 s timeout, permit without calls), configurable in the options. It must match the server's 2.4 policy so the server doesn't send GOAWAY for too many pings. |
| 6.2 | CDN-001, CDN-002, CGO-003, CJV-004, CPY-001, CPY-003 | Error mapping: a server-sent `Cancelled` is not caller cancellation, `NotFound`/`FailedPrecondition` on a session becomes the session-lost error, stream errors go through typed mapping, unknown enum values fall back to a number, and the status code is preserved. |
| 6.3 | CDN-008, CGO-007, CJV-006, CPY-004 | A missing reply payload raises a protocol error instead of returning handle 0. |
| 6.4 | CDN-003, CDN-005, CDN-006, CJV-001, CJV-005, CGO-004, CGO-006 | Stream and channel lifecycle: dispose cancels any in-flight read first, `close()` → `shutdownNow()` + await, an interrupt cancels the RPC, the stream ctx is cancelled on EOF, channel close order is fixed, and the owned handler and cert are disposed. |
| 6.5 | CRS-002, CRS-003, CDN-010, CGO-002 | Secret hygiene: scrub all error variants, redact the `tonic::Status` Display/Debug, redact `--value` only as a whole token, and attach the API key per call so a caller interceptor can't drop it. |
| 6.6 | CDN-011, CGO-008, CRS-004, CPY-005, CDN-009 | CLI batch mode reuses one channel. Streaming commands are exempt from the 30 s global timeout. `bench-read-bulk` backs off on failure. |
| 6.7 | CJV-002, CJV-007, CDN-007, CGO-005, CPY-006 | Java Galaxy client honours lenient TLS. Correlation ids use a non-blocking RNG. Don't retry `ResourceExhausted`. `dialConnected` returns the real cause. Python `smoke` attaches the stream before advising. |
**Verify:** dotnet `slnx` build + tests; Go `gofmt`/`go test ./...`; Rust `fmt`/`clippy -D warnings`/`test`; Python `pytest` (keep the generated code on the grpcio 1.80 pin); Java `JAVA_HOME=/opt/homebrew/opt/openjdk@17 gradle test`, then revert the generated-proto churn. Finish with the cross-language e2e matrix against windev.
---
## Order and effort (rough)
| Phase | Priority | Size | Needs windev |
|---|---|---|---|
| 0 Authz / throttle | p0 | M | no |
| 1 Land perf branches + WIP-001 | p1 | S (rebase) + S | yes |
| 2 Lifecycle | p1 | M | partly (2.11) |
| 3 Alarms | p1 | M–L | yes (+ rig) |
| 4 Conversion | p2 | M | yes |
| 5 Perf | p2/p3 | M | partly |
| 6 Clients | p2 | L | e2e only |
Findings marked **Plausible** in the area reports (for example WIP-001, MXA-004/005, SEC-006/007, the keepalive hangs) get a reproducing test first. If it does not reproduce, close the finding with that evidence and don't change the code.
@@ -0,0 +1,43 @@
# Bug and Performance Review — 2026-12-02
Full-codebase review at `main` `54367e74`, scoped to **correctness bugs and performance only** (no style or docs findings). Eight parallel reviewers each covered one area and wrote a per-area report in this directory. Everything was found by reading the code: nothing was built, run or exercised live. The fix plan is in [PLAN.md](PLAN.md).
## Reports
| Area | Report | Prefix | High | Medium | Low |
|---|---|---|---|---|---|
| Server: Sessions + gRPC | [server-sessions-grpc.md](server-sessions-grpc.md) | `SES` | 3 | 2 | 3 |
| Server: Workers, Metrics, Diagnostics | [server-workers-metrics.md](server-workers-metrics.md) | `WRK` | 0 | 2 | 8 |
| Server: Dashboard | [server-dashboard.md](server-dashboard.md) | `DSH` | 2 | 4 | 4 |
| Server: Security, Configuration, Alarms | [server-security-config-alarms.md](server-security-config-alarms.md) | `SEC` | 3 | 5 | 6 |
| Worker: MxAccess | [worker-mxaccess.md](worker-mxaccess.md) | `MXA` | 2 | 4 | 5 |
| Worker: IPC, STA, Conversion, Bootstrap | [worker-ipc-sta-conversion.md](worker-ipc-sta-conversion.md) | `WIP` | 2 | 3 | 5 |
| Clients: .NET + Go | [clients-dotnet-go.md](clients-dotnet-go.md) | `CDN` / `CGO` | 0 | 5 | 14 |
| Clients: Rust + Java + Python | [clients-rust-java-python.md](clients-rust-java-python.md) | `CRS` / `CJV` / `CPY` | 0 | 6 | 11 |
| **Total** | | | **12** | **31** | **56** |
Each report gives location, failure scenario, suggested fix, test idea and a confidence rating (Confirmed / Plausible) for every finding.
## High findings
| ID | Category | Finding |
|---|---|---|
| SES-002 | Bug (authz) | `Invoke` and `CloseSession` are not owner-scoped. Another key with `events:read` can `Invoke(DrainEvents)` a session and steal its events, which never reach the owner's stream or replay ring. Spot-checked: `OwnerKeyId` is compared only in `EventStreamService.cs:58`. |
| SES-003 | Bug (authz) | `AddBufferedItem` has no case in `ApplyConstraintsAsync`, so it skips API-key read constraints. Spot-checked. |
| DSH-001 | Bug (authz) | `Routes.razor` uses a plain `RouteView`, so the `[Authorize(AlarmsPolicy)]` on `/alarms` is enforced only on a full page load. In-circuit navigation lets anonymous localhost reach the alarm feed. Spot-checked. `/admin/secrets` may be exposed the same way (unverified). |
| SEC-001 | Bug (security) | The gRPC failure limiter partitions on `context.Peer`, which includes the ephemeral port, so the per-peer throttle resets on every new connection. |
| SEC-002 | Bug (security) | The aggregate throttle runs before the verification cache, so an unauthenticated sprayer who knows a key id can lock out its legitimate holder. |
| SEC-005 | Bug | A restart of the alarm monitor clears its cache without sending Clear or provider-status frames, so alarms cleared during the gap stay active for feed subscribers. |
| MXA-001 | Bug | Alarm failover never engages, or falsely "recovers", when the wnwrap primary fails to subscribe: `PollOnce` is a silent no-op that resets the failure counter. |
| SES-001 | Bug | On host stop, Kestrel waits 30 s on open `StreamEvents`, then every worker is killed instead of closed gracefully. |
| DSH-002 | Bug | A failed dashboard live read drops the session without closing it, orphaning it and its x86 worker for the 30-minute lease. Repeated failures can exhaust `MaxSessions`. |
| WIP-001 | Bug | Under sustained heavy event load (about 700 ev/s or more for over 15 s), the unbounded message-pump drain starves STA commands and the activity stamp, so the session is killed as `StaHung`. |
| MXA-002 / WIP-002 | Performance | None of the `perf.md` worker fixes (record-info pin, dedicated drain thread, synchronous flush, single write per frame) are on `main`. They exist only on the local branches `feat/worker-perf-prototype` and `feat/gateway-relay-hops` (#236, #235), which `perf.md` measured cutting worker CPU from 45% to 0.3% of a core. |
## Patterns across areas
- **No gRPC keepalive anywhere.** Neither the server (SES-005) nor any of the five clients (CDN-004, CGO-001, CRS-001, CJV-003, CPY-002) sets HTTP/2 keepalive. A half-open connection hangs a deadline-less stream forever and pins the session against the owner's reconnect.
- **Payload-less replies read as handle 0.** Four clients return `0` or null from `Register` / `AddItem` / `AddItem2` when the reply lacks its payload (CDN-008, CGO-007, CJV-006, CPY-004).
- **CLI batch mode dials a new channel per line** in four clients (CDN-011, CGO-008, CRS-004, CPY-005).
- **Alarm pipeline state** is lost or wrong on restart, reconcile, late ack and bad quality (SEC-005–007, SEC-009, MXA-001, MXA-005, MXA-007, DSH-005).
- **Resume / `ReplayGap` plumbing is correct** in all five clients. No duplicate-event or lost-event defects were found there.
@@ -0,0 +1,211 @@
# Clients (.NET / Go) — Bugs and Performance Review
- Date: 2026-12-02
- HEAD: 54367e74
- Scope: `clients/dotnet/` (`ZB.MOM.WW.MxGateway.Client` library + `ZB.MOM.WW.MxGateway.Client.Cli`) and `clients/go/` (`mxgateway` package + `cmd/mxgw-go`). Generated code and tests excluded. The server (`src/ZB.MOM.WW.MxGateway.Server/Grpc/`, `Workers/WorkerClient.cs`) was read only to confirm what the wire actually carries.
- Method: read-only source review. No repo file was modified and no repo project was built. One language-level claim (CDN-003) was reproduced with a throwaway console program outside the repo. "Confirmed" means the defect is visible in the cited code; "Plausible" means the code path is confirmed but the runtime impact depends on network or server behaviour that was not reproduced.
Neither client implements automatic reconnect. Both expose `after_worker_sequence` resume and surface `ReplayGap` as a typed signal, and that plumbing is correct: Go clears `Event` on a gap result (`session.go:1130-1132`), .NET exposes it through `MxEventStreamItem` and consumes the `StreamAttached` sentinel in `OpenEventStreamAsync`. No duplicate-event or lost-event defect was found in the resume path itself. The findings are about what happens around it: how stream and call termination is classified, liveness on a dead connection, disposal, and credential attachment.
## Summary
| ID | Severity | Category | Confidence | Title |
|---|---|---|---|---|
| CDN-001 | Medium | Bug | Confirmed | Server-sent `Cancelled` is mapped to `OperationCanceledException` even when the caller never cancelled |
| CDN-002 | Medium | Bug | Confirmed | Session loss arrives as gRPC `NotFound` / `FailedPrecondition` and is never mapped to `MxGatewaySessionException` |
| CDN-003 | Medium | Bug | Confirmed (mechanism reproduced; timing against real gRPC not) | `MxGatewayEventStream.DisposeAsync` throws `NotSupportedException` when a read is in flight |
| CDN-004 | Medium | Bug | Plausible | No HTTP/2 keepalive on the `SocketsHttpHandler`; deadline-less streams hang forever on a half-open connection |
| CDN-005 | Low | Bug | Confirmed | `MxGatewaySession.DisposeAsync` can block for about a minute and can throw `OperationCanceledException` |
| CDN-006 | Low | Performance | Confirmed | Owned `SocketsHttpHandler` (and pinned CA certificate) is never disposed with the channel |
| CDN-007 | Low | Performance | Confirmed | `ResourceExhausted` is retried as transient although every source of it is deterministic |
| CDN-008 | Low | Bug | Confirmed | `RegisterAsync` / `AddItemAsync` / `AddItem2Async` dereference a null `ReturnValue` on a payload-less reply |
| CDN-009 | Low | Bug | Confirmed | CLI: 30 s global cancellation applies to `stream-events` / `stream-alarms` / `bench-read-bulk`, and the resulting `OperationCanceledException` escapes unhandled |
| CDN-010 | Low | Bug | Confirmed | CLI: `--value` text is redacted from every error message, garbling diagnostics for short values |
| CDN-011 | Low | Performance | Confirmed | CLI batch mode builds a new channel (and a second one for Galaxy) per line |
| CGO-001 | Medium | Bug | Plausible | No keepalive dial option; deadline-less streams hang forever on a half-open connection |
| CGO-002 | Low | Bug | Confirmed | API key is attached only by dial-time interceptors: `NewClient` ignores `Options.APIKey`, and a caller `WithUnaryInterceptor` replaces auth |
| CGO-003 | Low | Bug | Confirmed | A stream ended by a context deadline or a server-sent `Canceled` closes the channel with no error |
| CGO-004 | Low | Performance | Confirmed | Stream context is never cancelled on EOF / terminal error; `Events`/`EventsAfter` leak one `cancelCtx` per stream |
| CGO-005 | Low | Bug | Confirmed | `dialConnected` waits the full timeout on an immediate failure and discards the real cause |
| CGO-006 | Low | Bug | Confirmed | `WatchDeployEvents` closes `errs` before `events`; the CLI can return with buffered events unprinted |
| CGO-007 | Low | Bug | Confirmed | `Register` / `AddItem` / `AddItem2` return handle `0` on a reply without the payload |
| CGO-008 | Low | Performance | Confirmed | CLI batch mode does a blocking dial per line; `bench-read-bulk` spins on failures with no backoff |
---
## .NET
### CDN-001 — Server-sent `Cancelled` is mapped to `OperationCanceledException` even when the caller never cancelled
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcMxGatewayClientTransport.cs:238-248`, `GrpcGalaxyRepositoryClientTransport.cs:120-130` (same code). Server origins: `src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs:1077-1081` (any server-side `OperationCanceledException`), `:1142` (`WorkerClientErrorCode.GatewayShutdown => StatusCode.Cancelled`), `src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs:491-494` and `:1142-1146` (pending commands completed with `GatewayShutdown` when the worker client is closed or disposed).
- Description: `MapRpcException` returns an `OperationCanceledException` when `cancellationToken.IsCancellationRequested || exception.StatusCode == StatusCode.Cancelled`. The second arm fires for a status the gateway itself produced. The server completes every pending command with `GatewayShutdown` when a session's worker client is closed (session closed by another caller, dashboard Close/Kill, lease reaper, gateway shutdown), and that maps to gRPC `Cancelled`. The exception is also constructed with the caller's token, which is not cancelled. `DotnetClientDesign.md:157-158` states the intended rule: surface `OperationCanceledException` "only when the caller initiated cancellation".
- Failure scenario: A client has `WriteAsync` in flight when an administrator kills the session from the dashboard, or the gateway service is stopped for a deploy. The call throws `OperationCanceledException`. Application code that follows the usual convention (`catch (OperationCanceledException) { return; }` meaning "we are shutting down") swallows it: the write outcome is unknown, no error is logged, and no reconnect is attempted. The same exception also bypasses `MxGatewaySession.DisposeAsync`'s catch filter (CDN-005) and the CLI's top-level handler (CDN-009).
- Suggested fix: Map to `OperationCanceledException` only when the caller's token is cancelled. Map a `Cancelled` status with a live token to `MxGatewayException` (or a typed "gateway shutting down / session closed" subtype) keeping the `RpcException` as inner.
- Test idea: Fake transport call that throws `RpcException(Status(Cancelled))` with a non-cancelled token; assert `InvokeAsync` throws `MxGatewayException`, not `OperationCanceledException`. Keep the existing caller-cancel test asserting OCE.
### CDN-002 — Session loss is never mapped to `MxGatewaySessionException`
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcMxGatewayClientTransport.cs:250-263` (status switch handles only `Unauthenticated`, `PermissionDenied`, `ResourceExhausted`), `MxCommandReplyExtensions.cs:59-66` (the only place `MxGatewaySessionException` is created). Server: `src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs:1106-1107` (`SessionNotFound => StatusCode.NotFound`, `SessionNotReady => StatusCode.FailedPrecondition`).
- Description: `MxGatewaySessionException` is built only from a reply whose `ProtocolStatus.Code` is `SessionNotFound` or `SessionNotReady`. The gateway never returns those codes in a reply: the `MxAccessGrpcMapper.SessionNotFound/SessionNotReady` helpers have no callers in the server, and `Invoke`, `StreamEvents` and `CloseSession` all throw `RpcException(NotFound)` / `RpcException(FailedPrecondition)` instead. `MapRpcException` sends both to the base `MxGatewayException`. The typed exception is therefore unreachable for the case it exists for.
- Failure scenario: The gateway restarts (orphan workers are terminated, sessions are gone). A client resumes with `StreamEventsAsync(afterWorkerSequence)` or issues a command and gets `NotFound`. Its recovery code `catch (MxGatewaySessionException) { reopen and re-subscribe }` never runs; the error lands in the generic `catch (MxGatewayException)` branch, which typically retries the same dead session id until it gives up. The only way to tell "session gone, reopen" from "transient, resume" is to dig `((RpcException)ex.InnerException).StatusCode` out by hand.
- Suggested fix: In `MapRpcException`, map `NotFound` and `FailedPrecondition` to `MxGatewaySessionException` (carrying the status detail and inner `RpcException`). Consider exposing the gRPC `StatusCode` on `MxGatewayException` so callers do not need the inner exception.
- Test idea: Fake transport throwing `RpcException(Status(NotFound, "Session x was not found."))` from `InvokeAsync` and from the event stream; assert `MxGatewaySessionException`.
### CDN-003 — `MxGatewayEventStream.DisposeAsync` throws when a read is in flight
- Severity: Medium. Category: Bug. Confidence: Confirmed for the mechanism (reproduced in isolation: 199 of 200 iterations threw); the exact timing against a live gRPC call was not reproduced.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayEventStream.cs:67-83` (dispose), `:59` (the in-flight `MoveNextAsync`), `:95` (`_enumerator` is the compiler-generated iterator from `GrpcMxGatewayClientTransport.StreamEventsAsync`, `GrpcMxGatewayClientTransport.cs:82-113`).
- Description: `DisposeAsync` cancels `_lifetime` and immediately calls `_enumerator.DisposeAsync()`. A compiler-generated async iterator throws `NotSupportedException` from `DisposeAsync` while a `MoveNextAsync` is still pending. `CancelAsync` only guarantees the cancellation callbacks have run; the iterator's continuation that observes the cancelled read is scheduled separately, so the iterator is normally still suspended at its `await`. `OpenAsync` in the same file already knows this rule and awaits the pending read before disposing (`:137-150`, "An async iterator cannot be disposed while a MoveNext is in flight"); `DisposeAsync` does not.
- Failure scenario: The documented usage is "Dispose to end the call". A consumer task sits in `await foreach (var e in stream.ReadAllAsync())` waiting for the next event. A shutdown path on another task calls `await stream.DisposeAsync()`. It throws `NotSupportedException` out of the dispose (and out of any `await using` scope), which most shutdown code does not expect. The `finally` still disposes `_lifetime` while the reader is unwinding. The underlying call is cancelled, so nothing leaks, but shutdown reports a spurious failure.
- Suggested fix: Track the in-flight `MoveNextAsync` task (or a reader-completion `TaskCompletionSource`) in `ReadAllAsync`; in `DisposeAsync`, after `CancelAsync`, await it (swallowing its exception) before `_enumerator.DisposeAsync()`, mirroring `OpenAsync`.
- Test idea: Fake transport whose stream awaits a `TaskCompletionSource` created with `RunContinuationsAsynchronously` and cancelled by token registration. Start `ReadAllAsync` on one task, call `DisposeAsync` from another, assert it completes without throwing and the reader ends with `OperationCanceledException`.
### CDN-004 — No HTTP/2 keepalive; deadline-less streams hang on a half-open connection
- Severity: Medium. Category: Bug. Confidence: Plausible (absence of configuration confirmed; hang not reproduced).
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClient.cs:398-403`, `GalaxyRepositoryClient.cs:538-543` (handler sets only `ConnectTimeout` and TLS), `MxGatewayClientOptions.cs:56` (`StreamTimeout` defaults to null, so streams carry no deadline).
- Description: The `SocketsHttpHandler` leaves `KeepAlivePingDelay`, `KeepAlivePingTimeout` and `KeepAlivePingPolicy` at their defaults (pings disabled). A server-streaming call only reads, so when the peer disappears without a FIN/RST there is no outbound data whose retransmission would fail. Nothing ever completes the pending `MoveNext`.
- Failure scenario: The gateway host loses power, or a firewall silently drops the idle flow. A client inside `await foreach` over `StreamEventsAsync`, `StreamAlarmsAsync` or `WatchDeployEventsAsync` sees no events and no exception, indefinitely. Its reconnect loop never runs because nothing ended. Tag values go stale with no signal. The only escape is the `Create(GrpcChannel, ...)` overload with a caller-configured handler; `Create(options)` offers no knob.
- Suggested fix: Set `KeepAlivePingDelay` (for example 30 s), `KeepAlivePingTimeout` (for example 10 s) and `KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always` on the handler, optionally exposed through `MxGatewayClientOptions`.
- Test idea: Unit test on `CreateHttpHandlerForTests` asserting the ping settings. Integration: start a stream through a TCP proxy, black-hole the proxy, assert the stream faults within ping delay + timeout.
### CDN-005 — `MxGatewaySession.DisposeAsync` can block for about a minute and can throw
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs:1713-1729`, `:44-70` (`CloseAsync`), `MxGatewayClient.cs:188-198` and `:374-388` (close goes through the retry pipeline), `MxGatewayClientRetryOptions.cs` defaults (`MaxAttempts = 2`, `MaxDelay = 2 s`), `MxGatewayClientOptions.cs` (`DefaultCallTimeout = 30 s`).
- Description: `DisposeAsync` calls `CloseAsync()` with no cancellation token. `CloseSessionRawAsync` is retried on `Unavailable` / `DeadlineExceeded`, each attempt with its own 30 s deadline. The catch filter covers `MxGatewayException`, `ObjectDisposedException` and `RpcException` but not `OperationCanceledException`.
- Failure scenario: (1) The gateway is unreachable through a black-holing network path. `await using var session = ...` leaving scope waits 30 s for attempt one, backs off, waits 30 s for attempt two: about 62 s before the application can continue shutting down. (2) The gateway is shutting down while the close is in flight and answers `Cancelled`; via CDN-001 that becomes `OperationCanceledException`, which escapes the filter, so `DisposeAsync` throws and masks whatever exception was already propagating through the `await using`.
- Suggested fix: Use a short bounded token for the dispose-time close (for example 5 s, single attempt) and add `OperationCanceledException` to the swallowed set.
- Test idea: Fake transport whose `CloseSessionAsync` never completes until its deadline; assert `DisposeAsync` returns within the bound. Second case: transport throws `OperationCanceledException`; assert dispose does not throw.
### CDN-006 — Owned `SocketsHttpHandler` is never disposed with the channel
- Severity: Low. Category: Performance (resource leak). Confidence: Confirmed.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClient.cs:79-88` and `:317-331`, `GalaxyRepositoryClient.cs:87-95` and `:459-473`; pinned CA at `MxGatewayClient.cs:415`, `GalaxyRepositoryClient.cs:555`.
- Description: `Create(options)` builds a `SocketsHttpHandler` and passes it as `GrpcChannelOptions.HttpHandler` without setting `DisposeHttpClient = true`. Grpc.Net.Client only disposes a caller-supplied handler when that flag is set, so `_channel.Dispose()` leaves the handler and its connection pool alive. The `X509Certificate2 trustedRoot` captured by the validation callback is also never disposed.
- Failure scenario: An application that recreates the client on each reconnect attempt (a common recovery pattern) leaves one handler, its HTTP/2 connection and its pool timer behind per attempt until the pool's idle timeout scavenges the socket. During a long outage with a tight reconnect loop this accumulates sockets and handles on both the client and the gateway.
- Suggested fix: Set `DisposeHttpClient = true` on the owned-channel path (or keep the handler and dispose it in `DisposeAsync`), and dispose `trustedRoot` with it.
- Test idea: Create and dispose a client against a loopback listener; assert the server side observes the connection close promptly after `DisposeAsync`.
### CDN-007 — `ResourceExhausted` is retried as transient
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientRetryPolicy.cs:87-92`; applied to every Galaxy unary call (`GalaxyRepositoryClient.cs` `ExecuteSafeUnaryAsync`) and to `CloseSession` / `Ping` / `GetSessionState` / `GetWorkerInfo`.
- Description: Every source of `ResourceExhausted` reachable on the retried calls is deterministic over the retry window: the auth failure limiter (`src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:133-135`, "Too many authentication attempts"), and Grpc.Net.Client's own "received message exceeds the maximum configured message size".
- Failure scenario: `DiscoverHierarchyAsync` requests pages of 5000 objects. On a large Galaxy a page with attributes exceeds `MaxGrpcMessageBytes` (16 MiB). The client downloads up to 16 MiB, fails with `ResourceExhausted`, waits, then makes the gateway run the same SQL page and re-download it before failing identically. With a raised `MaxAttempts` the waste multiplies. For the auth limiter, the retry just sends another request into the throttle window.
- Suggested fix: Drop `ResourceExhausted` from `IsTransientStatus`, or retry it only when the trailer reason marks it as transient.
- Test idea: Fake transport returning `ResourceExhausted` once; assert exactly one attempt is made.
### CDN-008 — `RegisterAsync` / `AddItemAsync` / `AddItem2Async` dereference a null `ReturnValue`
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs:84`, `:126`, `:177`.
- Description: These three still use `reply.X?.Handle ?? reply.ReturnValue.Int32Value`. `ReturnValue` is a message field and is null when unset, so an OK reply with neither the typed payload nor a return value throws `NullReferenceException`; a return value of a different kind silently yields `0`. `AddBufferedItemAsync`, `AuthenticateUserAsync` and `ArchestraUserToIdAsync` were moved to `ResolveInt32Result` (`:1408-1427`), whose own comment calls the NRE "historical"; the three most-used helpers were not.
- Failure scenario: A worker/gateway version skew returns an OK `Register` reply without the `register` payload. The caller gets a `NullReferenceException` with no session or correlation context instead of `MxGatewayMalformedReplyException`, or a handle of `0` that is then used for `AddItem`.
- Suggested fix: Route all three through `ResolveInt32Result`.
- Test idea: Fake transport returning `MxCommandReply { ProtocolStatus = Ok }` for Register/AddItem/AddItem2; assert `MxGatewayMalformedReplyException`.
### CDN-009 — CLI: global 30 s cancellation hits streaming and bench commands; `OperationCanceledException` escapes unhandled
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs:467-482` (`CreateCancellation`: only `galaxy-watch` / `galaxy-browse` are exempt), `:176` (top-level catch excludes `OperationCanceledException`), `:1474` and `:1543` (stream commands swallow it), `:1145-1260` (bench), `Program.cs:3` (no catch).
- Description: Every command other than `galaxy-watch` / `galaxy-browse` runs under a `CancellationTokenSource` cancelled after `--timeout` (default 30 s). (a) `stream-events` and `stream-alarms` without `--timeout` stop after 30 s and exit 0 with no message, indistinguishable from a server-ended stream. (b) `bench-read-bulk` defaults to 3 s warm-up + 30 s measurement, so with default arguments it is always cancelled mid-run; `scripts/bench-read-bulk.ps1:123-125` works around this by passing a larger `--timeout`. (c) For any non-stream command the `OperationCanceledException` is excluded by the only catch in `RunCoreAsync` and `Program.cs` has none, so the process dies with an unhandled-exception stack trace instead of a redacted error line and exit code 1. `--json` callers get no JSON error object.
- Failure scenario: `mxgw-dotnet stream-events --session-id X` used as a long-running tail silently ends after 30 s. `mxgw-dotnet read-bulk ... --timeout 2s` against a slow gateway crashes with `Unhandled exception. System.OperationCanceledException` and a runtime abort exit code.
- Suggested fix: Add `stream-events`, `stream-alarms` and `bench-read-bulk` to the long-running set (or derive the bench budget from its duration). Catch `OperationCanceledException` at the top level and emit a "timed out after <timeout>" error with exit code 1.
- Test idea: CLI test with a fake client whose `InvokeAsync` never completes and `--timeout 100ms`; assert exit code 1 and a JSON error on stderr rather than a thrown exception.
### CDN-010 — CLI: `--value` text is redacted from every error message
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs:183-189`, `MxGatewayCliSecretRedactor.cs` (ordinal `Replace` of each secret).
- Description: The top-level error handler passes `arguments.GetOptional("value")` as a secret for all commands, not only `write-secured*`. Any occurrence of the value string in the error message is replaced with `[redacted]`, with no minimum length.
- Failure scenario: `mxgw-dotnet write --value 0 ...` fails with `MXAccess command failed. kind=Write; hresult=0x80004005; ...`. The operator sees `hresult=[redacted]x8[redacted][redacted][redacted]4[redacted][redacted]5` and a session id with every `0` replaced. The HRESULT, the one thing needed to diagnose the failure, is destroyed.
- Suggested fix: Redact `--value` only for the secured-write commands, and skip redaction (or redact whole tokens only) for values shorter than a few characters.
- Test idea: CLI test: `write --value 0` with a fake client throwing an `MxAccessException` whose message contains `0x80004005`; assert the HRESULT text survives.
### CDN-011 — CLI batch mode builds a new channel per line
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location: `clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs:98` (client created inside `RunCoreAsync`), `:216-280` (`RunBatchAsync` calls `RunCoreAsync` per line), `MxGatewayCliClientAdapter.cs:19-20` (Galaxy commands create a second `GrpcChannel` instead of sharing the first).
- Description: Each batch line constructs a `GrpcChannel` + `SocketsHttpHandler`, performs a fresh TCP/TLS/HTTP/2 handshake, and disposes the channel (leaving the handler behind, CDN-006). Galaxy commands open a second independent channel to the same endpoint.
- Failure scenario: The cross-language e2e harness drives hundreds of commands through `batch`. Each pays a full connection setup, which dominates per-command latency and defeats the purpose of a persistent batch process.
- Suggested fix: Cache the client in `RunBatchAsync` keyed by the resolved connection options and reuse it across lines; build the Galaxy client with `GalaxyRepositoryClient.Create(channel, options)` over the same channel.
- Test idea: Batch test with a counting `clientFactory`; assert one client for N lines with identical connection options.
---
## Go
### CGO-001 — No keepalive; deadline-less streams hang on a half-open connection
- Severity: Medium. Category: Bug. Confidence: Plausible (absence of configuration confirmed; hang not reproduced).
- Location: `clients/go/mxgateway/client.go:62-67`, `clients/go/mxgateway/galaxy.go:98-103` (dial options: credentials + two interceptors only), `client.go:169-180` (`StreamEventsRaw` applies no deadline, by design).
- Description: No `grpc.WithKeepaliveParams` is set, so grpc-go sends no HTTP/2 pings. A server-streaming `Recv` on a connection whose peer vanished without FIN/RST never returns.
- Failure scenario: Same as CDN-004. The receive goroutine in `subscribeEventsAfter` (`session.go:1119-1148`) blocks in `stream.Recv()` forever; the consumer's channel neither delivers nor closes, so a reconnect loop built on "channel closed or `Err` set" never triggers. Callers can work around it through `Options.DialOptions`, but the default is the unsafe one.
- Suggested fix: Add a default `grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: 30 * time.Second, Timeout: 10 * time.Second, PermitWithoutStream: false})` ahead of `opts.DialOptions` so callers can still override. Confirm the gateway's Kestrel ping policy tolerates the interval.
- Test idea: Stream through a TCP proxy, black-hole it, assert the subscription delivers an `Err` result within Time + Timeout.
### CGO-002 — API key is attached only by dial-time interceptors
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/go/mxgateway/client.go:62-67` and `:79-85`, `clients/go/mxgateway/galaxy.go:98-103` and `:116-122`, `clients/go/mxgateway/auth.go:12-22`.
- Description: Two ways to lose the `authorization` header without any error at construction time. (1) `NewClient(conn, opts)` / `NewGalaxyClient(conn, opts)` store `opts` but never use `opts.APIKey`; the header is added only by the interceptors `Dial` installs. (2) `Dial` appends `opts.DialOptions` after its own `grpc.WithUnaryInterceptor` / `grpc.WithStreamInterceptor`. Those two options are last-wins in grpc-go, so a caller passing its own single interceptor (tracing, metrics) replaces the auth interceptor.
- Failure scenario: A service shares one `*grpc.ClientConn` and calls `mxgateway.NewClient(conn, mxgateway.Options{APIKey: key})`. Every RPC fails with `Unauthenticated` although a key was supplied; repeated failures also feed the gateway's per-peer auth failure limiter. Likewise `Options{APIKey: key, DialOptions: []grpc.DialOption{grpc.WithUnaryInterceptor(otelInterceptor)}}` authenticates streams but not unary calls.
- Suggested fix: Install auth with `grpc.WithChainUnaryInterceptor` / `grpc.WithChainStreamInterceptor` (or `grpc.WithPerRPCCredentials`) so it composes with caller interceptors, and have `Client`/`GalaxyClient` call `authContext(ctx, c.opts.APIKey)` themselves when constructed through `NewClient` (guarding against double-append on the `Dial` path).
- Test idea: bufconn server asserting the `authorization` metadata; cover `NewClient(conn, Options{APIKey})` and `Dial` with a caller `WithUnaryInterceptor`.
### CGO-003 — Stream ended by a deadline or a server-sent `Canceled` closes the channel with no error
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/go/mxgateway/session.go:1138-1140`, `clients/go/mxgateway/galaxy.go:253-258`. Server origins of `Canceled`: `src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs:1077-1081`, `:1142`.
- Description: The receive goroutine returns silently when `err == io.EOF || status.Code(err) == codes.Canceled || streamCtx.Err() != nil`. Two of those are not caller cancellations: a `Canceled` status produced by the gateway (it maps any server-side cancellation and `GatewayShutdown` to `Canceled`), and a parent-context deadline (`streamCtx.Err()` is `DeadlineExceeded`). All three look identical to the consumer: a closed channel with no `Err` result, the same as a clean server end after `CloseSession`.
- Failure scenario: A caller derives `ctx` with a 30 s timeout intended for "the subscribe call" and passes it to `SubscribeEvents`. After 30 s the events channel closes with no error. The consumer logs "stream ended" and treats the session as closed. In the gateway-shutdown case the correct reaction is to reconnect; in the clean-EOF case the session is gone. The consumer cannot tell which without probing.
- Suggested fix: Return silently only when `errors.Is(streamCtx.Err(), context.Canceled)`. Deliver a terminal `EventResult{Err: &GatewayError{...}}` for `DeadlineExceeded` and for a `Canceled` status received while `streamCtx` is still live.
- Test idea: bufconn server that ends `StreamEvents` with `status.Error(codes.Canceled, ...)`; assert a terminal `Err` result. Second case: parent context with a short deadline; assert an `Err` wrapping `context.DeadlineExceeded`.
### CGO-004 — Stream context is never cancelled on EOF / terminal error
- Severity: Low. Category: Performance (leak). Confidence: Confirmed.
- Location: `clients/go/mxgateway/session.go:1105-1155` (goroutine exits at `:1139` and `:1146` without calling `cancel`), `:1087-1093` (`EventsAfter` discards the `EventSubscription`, the only holder of `cancel`).
- Description: `subscribeEventsAfter` creates `streamCtx, cancel := context.WithCancel(ctx)`. `cancel` runs only from `EventSubscription.Close` or the slow-consumer branch. When the stream ends by EOF or a terminal error, the goroutine returns without cancelling, so the child context stays registered in the parent's children set until the parent is cancelled. For `Events` / `EventsAfter` the caller has no handle to cancel at all.
- Failure scenario: A long-running collector holds one cancellable root context for its lifetime and reconnects with `EventsAfter(rootCtx, lastSeq)` whenever the stream drops. Each reconnect leaves one `cancelCtx` (and whatever it references) attached to `rootCtx`. Over weeks of flapping this is unbounded growth and a progressively slower root cancel.
- Suggested fix: `defer cancel()` at the top of the receive goroutine.
- Test idea: Parent `context.WithCancel`; open and server-EOF N streams via `Events`; assert the `streamCtx` passed to a fake `StreamEventsRaw` reports `Err() != nil` after each stream ends.
### CGO-005 — `dialConnected` waits the full timeout and discards the cause
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/go/mxgateway/client.go:285-298`.
- Description: The loop returns only on `Ready`, `Shutdown`, or context expiry. `TransientFailure` is treated like any other state, so a connection that fails instantly (connection refused, TLS verification failure, bad `ServerNameOverride`) keeps cycling through backoff until `DialTimeout` (default 10 s) elapses. The returned error is `ctx.Err()`; the transport's actual error is never surfaced.
- Failure scenario: An operator runs `mxgw-go ping -ca-cert wrong.pem ...`. The command hangs 10 s and prints `mxgateway: dial failed: context deadline exceeded`. Nothing indicates a certificate problem. In batch mode every line pays the same 10 s.
- Suggested fix: On `TransientFailure`, either fail fast or keep waiting but remember it and, on expiry, return an error that includes the last connection error (for example by issuing a cheap RPC with `grpc.WaitForReady(false)` and returning its status).
- Test idea: `Dial` to a closed local port with a 5 s timeout; assert it returns well under the timeout, or at least that the error text contains "connection refused".
### CGO-006 — `WatchDeployEvents` closes `errs` before `events`
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/go/mxgateway/galaxy.go:238-265` (`defer close(events)` then `defer close(errs)`, so `errs` closes first), `clients/go/cmd/mxgw-go/main.go:1716-1722`.
- Description: On teardown the goroutine closes `errs` and then `events`, while up to 16 events may still be buffered in `events`. A consumer selecting on both channels can observe `errs` closed (or the terminal error) before it has drained `events`. The CLI does exactly that: `case streamErr, ok := <-errs: if !ok { return nil }`.
- Failure scenario: The gateway completes the deploy stream right after emitting events. `galaxy-watch` has unread events buffered; `select` picks the closed `errs` case and returns, so the last events are never printed. A library consumer written the same way silently misses the final deploy notification.
- Suggested fix: Close `events` first and `errs` last (swap the defers), document "drain `events`, then read `errs`", and in the CLI set `errs = nil` when it closes rather than returning. A single result channel like `EventResult` would remove the ambiguity.
- Test idea: Fake stream returning three events then `io.EOF` while the consumer is not yet reading; run the CLI loop and assert all three are printed.
### CGO-007 — `Register` / `AddItem` / `AddItem2` return handle `0` on a payload-less reply
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/go/mxgateway/session.go:143-146`, `:199-202`, `:228-231`.
- Description: These fall back to `reply.GetReturnValue().GetInt32Value()`, which is `0` when the return value is absent or not an int32. `AuthenticateUser`, `ArchestrAUserToId` and `AddBufferedItem` (`:877-886`, `:918-927`, `:953-962`) check the oneof kind and return `MalformedReplyError`; the three most-used helpers do not.
- Failure scenario: Version skew produces an OK `AddItem` reply without the `add_item` payload. The caller receives item handle `0` and `nil` error, then advises and writes against handle `0`.
- Suggested fix: Apply the same kind check and `MalformedReplyError` to all three.
- Test idea: Fake `Invoke` returning an OK reply with no payload for each command; assert `errors.As(err, *MalformedReplyError)`.
### CGO-008 — CLI: blocking dial per batch line; bench loop spins on failure
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location: `clients/go/cmd/mxgw-go/main.go:1478-1505` (`runBatch` dispatches each line through `runWithIO`), `:1306-1321` (`dialForCommand` in every command), `:817-819` (warm-up loop) and `:829-837` (steady-state loop).
- Description: (a) Every batch line performs `mxgateway.Dial`, which blocks until the channel is READY (TCP + TLS + HTTP/2 preface), then closes the connection. (b) `runBenchReadBulk` counts a failed `ReadBulk` and immediately loops; the warm-up loop ignores errors entirely.
- Failure scenario: (a) Harness-driven batch runs pay a full handshake per command, and 10 s per command when the gateway is down (CGO-005). (b) The gateway drops mid-benchmark; `ReadBulk` fails in microseconds with `Unavailable`, and the loop issues failing RPCs as fast as the CPU allows for the rest of the window, producing a meaningless latency sample and a burst of load when the gateway returns.
- Suggested fix: Cache the dialed client across batch lines keyed by resolved options. In the bench loops, stop (or sleep briefly) after consecutive transport failures.
- Test idea: Batch test with a counting dial hook asserting one dial for N lines; bench test against a closed endpoint asserting the call count stays bounded.
@@ -0,0 +1,195 @@
# Clients (Rust / Java / Python) — Bugs and Performance Review
- Date: 2026-12-02
- HEAD: 54367e74
- Scope: `clients/rust/` (src + crates), `clients/java/` (client + CLI), `clients/python/src/zb_mom_ww_mxgateway{,_cli}`. Generated code, build output and tests excluded (tests read only to confirm behaviour).
- Method: read-only source review. Nothing was built or executed; "Confirmed" means the defect is visible in the cited code, "Plausible" means the code path is confirmed but the runtime impact depends on library/server behaviour that was not reproduced.
None of the three clients implements automatic reconnect: all expose `after_worker_sequence` resume and surface `ReplayGap` as a typed item, and that mapping is correct in all three (Rust `EventItem::from_event`, Java `MxEventStreamItem`, Python `_surface_replay_gaps`). No duplicate/lost-event defect was found in the client-side resume plumbing itself. The findings below are about liveness, cleanup, error mapping and secret hygiene around it.
## Summary
| ID | Severity | Category | Confidence | Title |
|---|---|---|---|---|
| CRS-001 | Medium | Bug | Plausible | No HTTP/2 or TCP keepalive on the tonic channel; deadline-less streams hang forever on a half-open connection |
| CRS-002 | Low | Bug | Confirmed | `attach_secrets` scrubs only `Error::MxAccess`; `Error::Command` from secured writes / `authenticate_user` keeps the unscrubbed reply |
| CRS-003 | Low | Bug | Plausible | Raw `tonic::Status` is retained and printed unredacted (`Error::Status` Display, Debug of every status variant) |
| CRS-004 | Low | Performance | Confirmed | CLI batch mode dials a new channel for every line |
| CJV-001 | Medium | Bug | Confirmed | `MxGatewayClient.close()` only calls `shutdown()`; open streams and their blocked readers survive it |
| CJV-002 | Medium | Bug | Confirmed | `GalaxyRepositoryClient` ignores the lenient-TLS default that `MxGatewayClient` honours |
| CJV-003 | Medium | Bug | Plausible | No keepalive on the Netty channel; same half-open hang as CRS-001 |
| CJV-004 | Low | Bug | Confirmed | `MxEventStream` / `DeployEventStream` rethrow raw `StatusRuntimeException`, bypassing typed mapping and redaction |
| CJV-005 | Low | Bug | Confirmed | `DeployEventStream.take()` does not cancel the RPC on interrupt |
| CJV-006 | Low | Bug | Confirmed | Typed helpers return `0` / empty list when the reply lacks the expected payload |
| CJV-007 | Low | Performance | Plausible | `SecureRandom` used for every command correlation id |
| CPY-001 | Medium | Bug | Confirmed | Enum `.Name()` raises `ValueError` on unknown values while building typed errors |
| CPY-002 | Medium | Bug | Plausible | No keepalive channel options; same half-open hang as CRS-001 |
| CPY-003 | Low | Bug | Confirmed | `map_rpc_error` drops the status code and does not redact credentials |
| CPY-004 | Low | Bug | Confirmed | `register` / `add_item` / `add_item2` return `0` on a reply without the payload |
| CPY-005 | Low | Performance | Confirmed | CLI batch mode runs a new event loop, channel and TOFU TLS probe per line |
| CPY-006 | Low | Bug | Plausible | `smoke` advises before attaching the event stream, so the initial value can be missed |
---
## Rust
### CRS-001 — No HTTP/2 or TCP keepalive; deadline-less streams hang on a half-open connection
- Severity: Medium. Category: Bug. Confidence: Plausible (absence of configuration confirmed; hang not reproduced).
- Location: `clients/rust/src/client.rs:181-194`, `clients/rust/src/galaxy.rs:176-189`, `clients/rust/src/options.rs:47-49` (`stream_timeout: None` default).
- Description: The `Endpoint` is configured with `connect_timeout` and TLS only. No `http2_keep_alive_interval`, `keep_alive_timeout`, `keep_alive_while_idle` or `tcp_keepalive` is set, and streaming RPCs carry no deadline unless the caller opts into `with_stream_timeout`. A grep across all three clients finds no keepalive setting anywhere.
- Failure scenario: A consumer holds `Session::events()` on slow-changing tags. A stateful firewall/NAT idles the flow out, or the gateway host loses power, without a FIN/RST reaching the client. `stream.next().await` never resolves and never errors, so the consumer never reaches its reconnect/`events_after` path. Meanwhile the gateway's 30 s detach grace and 300 s replay retention expire, so by the time anything notices, the session and its replay history are gone. Unary calls are bounded by `call_timeout`; streams are not.
- Suggested fix: Set `http2_keep_alive_interval` (for example 20–30 s), `keep_alive_timeout` (10 s) and `keep_alive_while_idle(true)` on the endpoint, exposed through `ClientOptions` with those defaults. Confirm the gateway's Kestrel ping-rate limits tolerate the interval.
- Test idea: Local TCP proxy between client and a fake server; open a stream, then make the proxy silently drop packets (no close). Assert the stream yields `Error::Unavailable`/`Transport` within interval + timeout.
### CRS-002 — `attach_secrets` scrubs only `Error::MxAccess`
- Severity: Low. Category: Bug. Confidence: Confirmed (code), Plausible (impact).
- Location: `clients/rust/src/session.rs:1215-1224` (used at 820, 853, 894); `clients/rust/src/error.rs:149-152` (`CommandError` derives `Debug` over the whole reply), `error.rs:171-185` (Display prints `protocol_status.message`).
- Description: For `write_secured`, `write_secured2` and `authenticate_user`, the error is passed through `attach_secrets`, which rewrites only the `Error::MxAccess` arm and returns every other variant untouched. A reply whose protocol status is anything other than `OK`/`MXACCESS_FAILURE` becomes `Error::Command(CommandError)`, whose Display prints `protocol_status.message` and whose derived `Debug` prints `diagnostic_message` and every `statuses[].diagnostic_text` verbatim. The Java (`invokeCommandRedacted`, `MxGatewaySession.java:1140-1162`) and Python (`_redact_error`, `session.py:979-1001`) clients scrub every error type; `Error::redact_secrets` in `error.rs:322-376` already does the right thing for most variants but is not used here and itself has no `Command` arm.
- Failure scenario: `authenticate_user` fails with a worker/protocol-level status (for example `WORKER_UNAVAILABLE` or `INVALID_REQUEST`) whose message or diagnostic echoes the supplied credential. The caller logs `{error}` or `{error:?}` and the verifier password lands in the log.
- Suggested fix: Add a `Command` arm (scrub the reply with `scrub_reply_strings`) to both `attach_secrets` and `Error::redact_secrets`, and route the other variants through `redact_secrets`.
- Test idea: Fake gateway returns `PROTOCOL_STATUS_CODE_INVALID_REQUEST` with the password in `protocol_status.message` and `diagnostic_message`; assert neither `to_string()` nor `format!("{:?}")` contains it.
### CRS-003 — Raw `tonic::Status` retained and printed unredacted
- Severity: Low. Category: Bug. Confidence: Plausible (requires the server or an intermediary to echo a credential).
- Location: `clients/rust/src/error.rs:379-405` (mapping), `error.rs:91-92` (`Status` variant), `error.rs:510-522` (`redact_credentials`).
- Description: `From<tonic::Status>` redacts only the copied `message` string. The original status is stored in `status: Box<tonic::Status>` and exposed through derived `Debug` and `source()`, both of which print the unredacted message and metadata. The catch-all arm (`_ => Self::Status(Box::new(status))`) does not redact at all, and its Display is `gateway status error: {0}`. `redact_credentials` also only matches whitespace-delimited tokens that *start* with `mxgw_`, so `"mxgw_…"`, `key=mxgw_…` or `(mxgw_…)` pass through.
- Failure scenario: A proxy or gateway error path returns `INTERNAL`/`INVALID_ARGUMENT` with the authorization value in the description; `eprintln!("{error}")` (as `mxgw-cli` `main.rs:42` does) prints the key.
- Suggested fix: Rebuild the stored status with the redacted message (as `redact_secrets::scrub_status` already does) in every arm including the catch-all, and make the redactor substring-based on the `mxgw_[A-Za-z0-9_-]+` shape.
- Test idea: `Error::from(Status::internal("bad header \"mxgw_id_secret\""))`; assert Display and Debug contain no `secret`.
### CRS-004 — CLI batch mode dials a new channel per line
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location: `clients/rust/crates/mxgw-cli/src/batch.rs:49-64`, `clients/rust/crates/mxgw-cli/src/connect.rs:7-21`. The Java CLI has the same shape (`MxGatewayCli.java:2066-2067`, every command `try (… clientFactory.connect(…))`); Python is CPY-005.
- Description: Batch mode exists to avoid per-command process start-up, but each dispatched line calls `GatewayClient::connect`, which builds a fresh `Channel` (TCP + optional TLS handshake + HTTP/2 settings, plus a CA-file read) and drops it at the end of the command.
- Failure scenario: The e2e matrix or a scripted run issues hundreds of commands; each pays connection set-up, dominating latency for small commands and churning gateway connections.
- Suggested fix: Cache one `GatewayClient`/`GalaxyClient` per distinct `ConnectionArgs` for the lifetime of `run_batch` and pass it into `dispatch`.
- Test idea: Count accepted connections on a fake server across N batch lines; expect 1.
---
## Java
### CJV-001 — `close()` only calls `shutdown()`; open streams and blocked readers survive
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location: `clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClient.java:369-374`, `GalaxyRepositoryClient.java:374-379`; reader side `MxEventStream.java:149-162`, `DeployEventStream.java:105-115`.
- Description: `close()` (the `AutoCloseable` path used by try-with-resources) calls `ownedChannel.shutdown()` and returns. `ManagedChannel.shutdown()` rejects new calls but lets existing calls run to completion. A `StreamEvents`/`StreamAlarms`/`WatchDeployEvents` call has no deadline by default (`streamTimeout` null), so it never completes; the channel never terminates, its Netty threads stay alive, the gateway keeps a subscriber slot, and any thread blocked in `MxEventStream.hasNext()` (`queue.take()`) stays blocked. Only `closeAndAwaitTermination()` escalates to `shutdownNow()`.
- Failure scenario: Application shuts down with `try (MxGatewayClient client = …)` while a worker thread iterates `session.streamEvents()`. `close()` returns immediately, the reader thread never wakes, and an executor `awaitTermination` on that thread times out. In default single-subscriber mode the still-open stream also occupies the session's only subscriber slot.
- Suggested fix: Track open stream handles in the client and cancel them in `close()`, or have `close()` call `shutdownNow()` after a short `awaitTermination`. Document the difference if `shutdown()` semantics are kept.
- Test idea: In-process server with a never-completing stream; start a reader thread on `hasNext()`, call `client.close()`, assert the reader returns/throws within a bound and `channel.isTerminated()` becomes true.
### CJV-002 — `GalaxyRepositoryClient` ignores the lenient-TLS default
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location: `GalaxyRepositoryClient.java:413-425` versus `MxGatewayClient.java:400-421`; contract at `MxGatewayClientOptions.java:107-115`.
- Description: `MxGatewayClient.createChannel` has four branches: plaintext, pinned CA, lenient (`!requireCertificateValidation()` → `InsecureTrustManagerFactory`), strict. `GalaxyRepositoryClient.createChannel` has only plaintext, pinned CA and `useTransportSecurity()`. With TLS, no CA file and the default `requireCertificateValidation=false`, the options contract says the gateway's self-signed certificate is accepted; the Galaxy client instead validates against the JVM trust store.
- Failure scenario: A deployment with a self-signed gateway certificate: `MxGatewayClient.connect(options)` works, `GalaxyRepositoryClient.connect(options)` with the same options fails every RPC with `UNAVAILABLE` (handshake failure). The Java CLI `galaxy-*` commands fail where the session commands succeed.
- Suggested fix: Move channel construction into one shared helper used by both clients.
- Test idea: Extend `MxGatewayClientTlsTests` to run the lenient-default case against `GalaxyRepositoryClient` with a self-signed in-process server.
### CJV-003 — No keepalive on the Netty channel
- Severity: Medium. Category: Bug. Confidence: Plausible.
- Location: `MxGatewayClient.java:392-426`, `GalaxyRepositoryClient.java:405-430`.
- Description: `NettyChannelBuilder` is built without `keepAliveTime` / `keepAliveTimeout` / `keepAliveWithoutCalls`; grpc-java's default disables keepalive. Combined with deadline-less streams this is the same half-open hang as CRS-001: `MxEventStream.hasNext()` blocks in `queue.take()` indefinitely and async observers never receive `onError`.
- Failure scenario: As CRS-001, for an Ignition module or service holding `streamEvents()` across a firewall idle timeout.
- Suggested fix: `builder.keepAliveTime(30, SECONDS).keepAliveTimeout(10, SECONDS)` with options to tune, coordinated with the server's ping policy.
- Test idea: As CRS-001 with a black-holing proxy; assert `hasNext()` throws within the keepalive bound.
### CJV-004 — Iterator streams rethrow raw `StatusRuntimeException`
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `MxEventStream.java:77-83` and `100-103`; `DeployEventStream.java:50-56` and `73-76`. Mapping that is skipped: `MxGatewayErrors.java:13-29`.
- Description: `onError` enqueues the gRPC `Throwable` as-is and `hasNext()` rethrows any `RuntimeException` unchanged. Every unary path maps through `MxGatewayErrors.fromGrpc` (typed `MxGatewayAuthenticationException` / `MxGatewayAuthorizationException`, credential redaction of the description); the two iterator streams do not. Only non-runtime throwables are wrapped in `MxGatewayException`.
- Failure scenario: An `events:read` key attaches to a session owned by another key. The gateway returns `PERMISSION_DENIED`; the caller's `catch (MxGatewayAuthorizationException | MxGatewayException e)` around the loop does not match and a raw `io.grpc.StatusRuntimeException` escapes, with its description unredacted. The same happens for `UNAUTHENTICATED` and `UNAVAILABLE`, so reconnect logic keyed on `MxGatewayException` never fires.
- Suggested fix: In `hasNext()`, pass `StatusRuntimeException` through `MxGatewayErrors.fromGrpc("stream events", …)` (keep the interrupt case distinguishable). `MxEventStreamTests` line 44 pins the raw type for the interrupt path and needs updating.
- Test idea: Feed `observer().onError(Status.PERMISSION_DENIED.asRuntimeException())`; assert `hasNext()` throws `MxGatewayAuthorizationException`.
### CJV-005 — `DeployEventStream.take()` does not cancel the RPC on interrupt
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `DeployEventStream.java:105-115` (compare `MxEventStream.java:149-162`, which cancels).
- Description: On `InterruptedException` the method restores the interrupt flag and returns a synthetic `CANCELLED` exception, but never calls `requestStream.cancel(…)`. `hasNext()` then marks the iterator ended. The underlying `WatchDeployEvents` call stays open until its 16-slot queue overflows; deploy events are rare, so in practice it stays open until the channel is torn down (and see CJV-001 for why `close()` does not do that).
- Failure scenario: A watcher thread is interrupted during shutdown or task cancellation and abandons the iterator without calling `close()`; the server-side watch subscription leaks for the life of the channel.
- Suggested fix: Cancel the request stream in the interrupt branch, as `MxEventStream` does.
- Test idea: Mirror `interruptCancelsCallAndRestoresInterruptFlag` for `DeployEventStream` and assert `cancelCount == 1`.
### CJV-006 — Typed helpers return `0` / empty list on a reply without the payload
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `MxGatewaySession.java:149-155` (`register`), `192-198` (`addItem`), `226-232` (`addItem2`), `354`, `374` and the other bulk helpers (`reply.getXxxBulk().getResultsList()`), `574-595` (`readBulk`), drain at `1097-1104`.
- Description: When the reply carries neither the typed payload nor an int32 `return_value`, protobuf default accessors yield `0` or an empty list and the helper returns it as a valid result. `MxGatewayMalformedReplyException` exists and the Rust client raises `MalformedReply` in the same positions (`session.rs:1110-1197`, `1287-1343`).
- Failure scenario: A contract mismatch (older/newer gateway, wrong reply arm) makes `register` return handle `0`; every following `addItem(0, …)` fails with an unrelated invalid-handle MXAccess error. `subscribeBulk` returning an empty list reads as "nothing subscribed, no failures".
- Suggested fix: Check `hasXxx()` / `getReturnValue().getKindCase()` and throw `MxGatewayMalformedReplyException` otherwise.
- Test idea: Fake stub returns an OK `MxCommandReply` with no payload; assert each helper throws.
### CJV-007 — `SecureRandom` for every command correlation id
- Severity: Low. Category: Performance. Confidence: Plausible (not measured).
- Location: `MxGatewaySession.java:77`, `1114-1120`, `1278-1282`.
- Description: Every `invokeCommand` draws 16 bytes from a shared static `SecureRandom` and hex-formats them. Correlation ids are diagnostic, not security tokens. `SecureRandom.nextBytes` is serialized internally, so concurrent callers on one JVM contend on it, and on some platforms it reads from the kernel.
- Failure scenario: A multi-threaded poller issuing high-rate `readBulk`/`write` calls sees lock contention in `SecureRandom` in profiles.
- Suggested fix: Use a per-process random prefix plus an `AtomicLong` counter (as the Rust client does), or `ThreadLocalRandom`.
- Test idea: JMH microbenchmark of `newCorrelationId()` at 1 and 16 threads before/after.
---
## Python
### CPY-001 — Enum `.Name()` raises `ValueError` on unknown values while building typed errors
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location: `clients/python/src/zb_mom_ww_mxgateway/errors.py:95` (`pb.ProtocolStatusCode.Name(code)`), `errors.py:169` (`pb.MxStatusCategory.Name(status.category)`).
- Description: proto3 enums are open, so a gateway newer than the client's generated code can send a numeric value the client has no name for. `EnumTypeWrapper.Name` raises `ValueError` for such values. Line 169 runs for every status entry whenever an `MxAccessError` message is built; line 95 runs when the protocol status message is empty. In both cases the `ValueError` replaces the typed gateway error. The Rust client (`try_from(...).unwrap_or(Unspecified)`) and Java (`UNRECOGNIZED`) tolerate this.
- Failure scenario: A gateway adds `MX_STATUS_CATEGORY_*` value 11 (or a new `ProtocolStatusCode`). A failing write on an older Python client raises `ValueError: Enum MxStatusCategory has no name defined for value 11` instead of `MxAccessError`; `except MxGatewayError` handlers and the CLI's `_run` wrapper do not catch it, and the secured-write redaction path (`_invoke_redacted` catches only `MxGatewayError`) is bypassed.
- Suggested fix: Use a small helper that falls back to `str(value)` on `ValueError`.
- Test idea: Build an `MxCommandReply` with `statuses[0].category = 99`; assert `ensure_mxaccess_success` raises `MxAccessError`. Same for `ensure_protocol_success` with code 999 and an empty message.
### CPY-002 — No keepalive channel options
- Severity: Medium. Category: Bug. Confidence: Plausible.
- Location: `clients/python/src/zb_mom_ww_mxgateway/options.py:189-205`; streams at `client.py:141-145`, `183-187`, `205-209`, `galaxy.py:260-271`; default `stream_timeout=None` at `options.py:31`.
- Description: `channel_options` contains only the two message-size limits and the optional target-name override. gRPC core keepalive is disabled by default for clients, and streams have no deadline unless `stream_timeout` is set. Same half-open hang as CRS-001: `async for item in session.stream_events()` never yields and never raises.
- Failure scenario: As CRS-001.
- Suggested fix: Add `grpc.keepalive_time_ms`, `grpc.keepalive_timeout_ms`, `grpc.keepalive_permit_without_calls` and `grpc.http2.max_pings_without_data=0` with sensible defaults, tunable via `ClientOptions`.
- Test idea: As CRS-001 with a black-holing proxy; assert the iterator raises `MxGatewayTransportError` within the keepalive bound.
### CPY-003 — `map_rpc_error` drops the status code and does not redact credentials
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/python/src/zb_mom_ww_mxgateway/errors.py:60-72`.
- Description: Only `UNAUTHENTICATED` and `PERMISSION_DENIED` get distinct types. `DEADLINE_EXCEEDED`, `UNAVAILABLE`, `RESOURCE_EXHAUSTED` and `CANCELLED` all become a bare `MxGatewayTransportError` with no `code` attribute, so a caller implementing reconnect/backoff must reach into `__cause__.code()`. The Rust client has `Timeout` / `Cancelled` / `Unavailable`. Separately, `details` is interpolated verbatim; Rust and Java pass it through a `mxgw_`/`Bearer` redactor, Python relies on each caller (the CLI does exact-match redaction in `_run`, library users get none).
- Failure scenario: A reconnect loop cannot tell "gateway unavailable, retry with backoff" from "deadline exceeded on a non-idempotent write, do not blindly retry" without inspecting the chained gRPC exception; code that only uses the public hierarchy retries both or neither.
- Suggested fix: Store `code` on `MxGatewayTransportError` (and/or add `MxGatewayTimeoutError`, `MxGatewayUnavailableError` subclasses), and run `details` through a credential redactor.
- Test idea: Map fake `RpcError`s for each code; assert distinct type or `.code`, and that a details string containing `Bearer mxgw_x_y` is redacted.
### CPY-004 — `register` / `add_item` / `add_item2` return `0` on a reply without the payload
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `clients/python/src/zb_mom_ww_mxgateway/session.py:97`, `146`, and the `add_item2` return that follows `157-168`; contrast with `session.py:724-726`, `752-754`, `782-784`, which raise `MalformedReplyError`.
- Description: These helpers read `reply.register.server_handle` / `reply.add_item.item_handle` without `HasField` or a `return_value` fallback, so a reply missing the payload silently yields handle `0`. The same module already raises `MalformedReplyError` for `authenticate_user`, `archestra_user_to_id` and `add_buffered_item`, and the Rust client does so for all of them.
- Failure scenario: As CJV-006: handle `0` flows into later calls and surfaces as an unrelated MXAccess invalid-handle failure.
- Suggested fix: Apply the existing `HasField` / int32 `return_value` / `MalformedReplyError` pattern to these three helpers (and the bulk helpers).
- Test idea: Fake stub returns an OK reply with no payload; assert `MalformedReplyError`.
### CPY-005 — CLI batch mode: new event loop, channel and TOFU probe per line
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location: `clients/python/src/zb_mom_ww_mxgateway_cli/commands.py:78-99`, `102-126`, `1460-1473`, `1529-1549`; probe at `zb_mom_ww_mxgateway/options.py:153-158`.
- Description: Each batch line re-enters Click, which calls `asyncio.run` (new loop), `GatewayClient.connect` (new `grpc.aio` channel) and, on the default lenient-TLS path, `ssl.get_server_certificate` — a separate blocking TCP+TLS handshake in a worker thread before the real channel handshake. So a TLS batch line costs two TLS handshakes plus loop and channel set-up and teardown.
- Failure scenario: Matrix or scripted batch runs against a TLS gateway spend most of their time in connection set-up; the gateway sees two short-lived connections per command.
- Suggested fix: Run the batch loop inside one event loop and reuse a client per distinct connection options; at minimum cache the resolved `ChannelSecurity` per endpoint for the process.
- Test idea: Count accepted TLS connections on a test server across N batch lines; expect 1–2 rather than 2N.
### CPY-006 — `smoke` advises before attaching the event stream
- Severity: Low. Category: Bug. Confidence: Plausible.
- Location: `clients/python/src/zb_mom_ww_mxgateway_cli/commands.py:1231-1241`; server behaviour at `src/ZB.MOM.WW.MxGateway.Server/Grpc/EventStreamService.cs:81-82` (fresh stream: "plain attach, no replay"); contract note at `mxaccess_gateway.proto:87-100`.
- Description: `_smoke` runs `register` → `add_item` → `advise` and only then opens `session.stream_events()` with `after_worker_sequence=0`. A fresh stream does not replay the ring, and the proto documents exactly this attach race as the reason `emit_stream_attached` exists. The initial `OnDataChange` for the advised item can be published before the subscriber registers.
- Failure scenario: Against a static tag the only event is the initial value; it is published before the stream attaches, `_collect_events` waits out `--timeout` and the smoke returns an empty `events` list, an intermittent failure in the cross-language matrix.
- Suggested fix: Open the stream before `advise` (request `emit_stream_attached=True` when the gateway advertises `stream-events-attached-ack` and wait for the sentinel), or attach with `after_worker_sequence` set so the ring is replayed.
- Test idea: Fake gateway that emits the initial event synchronously inside `Advise` and drops events with no subscriber; assert smoke still collects it.
@@ -0,0 +1,192 @@
# Server Dashboard — bug and performance review (2026-12-02)
Scope: `src/ZB.MOM.WW.MxGateway.Server/Dashboard/` at HEAD `54367e74`. Read-only review; no source was modified and nothing was built or run. Other code was read only to confirm a finding. All paths below are relative to `src/ZB.MOM.WW.MxGateway.Server/` unless they start with `src/`.
## Summary
| ID | Severity | Category | Confidence | Title |
|---|---|---|---|---|
| DSH-001 | High | Bug (security) | Confirmed | `/alarms` `AlarmsPolicy` is bypassed by in-circuit navigation (plain `RouteView`) |
| DSH-002 | High | Bug | Confirmed path / Plausible trigger | Live-read failure orphans the dashboard session and its x86 worker for the full 30-minute lease |
| DSH-003 | Medium | Performance | Confirmed | Every snapshot tick runs the full health-check set (Galaxy SQL ping included); a slow check stalls the tick and reports `Unknown` |
| DSH-004 | Medium | Performance | Confirmed code / Plausible magnitude | Session-details event pump renders once per wake with no time coalescing |
| DSH-005 | Medium | Bug | Confirmed | `/hubs/alarms` clients that connect after the publisher subscribed never receive the active-alarm snapshot |
| DSH-006 | Medium | Bug (security) | Confirmed | Hub-token and cookie lifetimes are not enforced on live hub connections or circuits |
| DSH-007 | Low | Bug | Plausible | Cancelled Browse read can leave tags advised on the worker but untracked |
| DSH-008 | Low | Performance | Confirmed | `NativeDialog` makes a JS interop call on every parent render once it has been opened |
| DSH-009 | Low | Performance | Confirmed | `AlarmsHubPublisher` has no idle gate |
| DSH-010 | Low | Performance | Confirmed | Alarms page re-sorts and re-renders every 3 s even when nothing changed |
Areas read and found sound (no finding): `DashboardSessionAcl` decision order and fallback arm, `EventsHubViewerRegistry` counting, `DashboardEventBroadcaster` pump/teardown locking, `DashboardSnapshotFeed` generation handling, `HubTokenService` mint/validate (anonymous principals mint a token that never validates), `/hubs/token` scheme restriction, page disposal of timers and `CancellationTokenSource`s.
---
## DSH-001 — `/alarms` `AlarmsPolicy` is bypassed by in-circuit navigation
- **Severity:** High — **Category:** Bug (security) — **Confidence:** Confirmed (code reading; not exercised in a browser)
- **Locations:**
- `Dashboard/Components/Routes.razor:4` — `<RouteView ...>`, not `AuthorizeRouteView`
- `Dashboard/Components/App.razor:13` — `<Routes @rendermode="InteractiveServer" />` (global interactive routing)
- `Dashboard/Components/Pages/AlarmsPage.razor:12` — `[Authorize(Policy = AlarmsPolicy)]` is the only gate; `OnInitialized` (212–216) starts the poll and feed loops unconditionally
- `Dashboard/DashboardEndpointRouteBuilderExtensions.cs:135-138` — endpoint-level `RequireAuthorization(ViewerPolicy)`
- `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmFeedAuthorizationTests.cs:144-159` — asserts endpoint metadata only
**Description.** The page attribute is enforced by endpoint routing on a full HTTP request to `/alarms`. With the router rendered interactively, a navigation that starts inside an existing circuit never issues an HTTP request for the page: the in-circuit `Router` resolves the route and `RouteView` renders it. `RouteView` does not evaluate `[Authorize]`; only `AuthorizeRouteView` does. `AlarmsPage` has no in-component check, and `IDashboardLiveDataService.QueryAlarmsAsync` / `IGatewayAlarmService.StreamAsync` take no principal.
**Failure scenario.** Anonymous localhost (`AllowAnonymousLocalhost=true`, the default) or any caller under `Authentication:Mode=Disabled` loads `/` — allowed by `ViewerPolicy`. The nav link is hidden (`MainLayout.razor:18-22`), but the caller runs `Blazor.navigateTo('/alarms')` in the console, or clicks any in-page anchor pointing at `/alarms`. The circuit renders `AlarmsPage` and the galaxy-wide alarm list is displayed. This is exactly the audience the contract says "do not receive it at all".
**Related.** `/admin/secrets` (shared `ZB.MOM.WW.Secrets.Ui` page) relies on the same attribute mechanism, so a Viewer can reach it the same way. Its mutating and reveal controls are separately wrapped in `AuthorizeView` in the library source, so the exposure there appears limited to the list itself. Not verified against the packaged 1.0.1 build.
**Suggested fix.** Switch `Routes.razor` to `AuthorizeRouteView` with a `NotAuthorized` fragment. Check that anonymous localhost still passes `ViewerPolicy` in-circuit, since `DashboardAuthorizationHandler` reads `IHttpContextAccessor`. As defense in depth, have `AlarmsPage` call `IAuthorizationService.AuthorizeAsync(user, AlarmsPolicy)` before starting its loops.
**Test idea.** bUnit: render `Routes` with an unauthenticated `AuthenticationState`, navigate the `NavigationManager` to `/alarms`, assert `AlarmsPage` is not instantiated and `IGatewayAlarmService.StreamAsync` is never called.
---
## DSH-002 — Live-read failure orphans the dashboard session and worker
- **Severity:** High — **Category:** Bug — **Confidence:** Confirmed code path; trigger frequency Plausible
- **Locations:**
- `Dashboard/DashboardLiveDataService.cs:179-184` — catch-all calls `InvalidateSession()`
- `Dashboard/DashboardLiveDataService.cs:541-546` — `InvalidateSession` nulls `_session` without closing it
- `Dashboard/DashboardLiveDataService.cs:482-497` — `EnsureReadyAsync` closes the old session only when `_session` is still non-null
- `Sessions/GatewaySession.cs:2276-2282` — a bulk reply with non-Ok `ProtocolStatus` throws `SessionManagerException` while the session stays Ready
- `Configuration/SessionOptions.cs:13,21,80` — `MaxSessions=64`, `DefaultLeaseSeconds=1800`, `UnattachedSessionGraceSeconds=0` (sweep disabled)
**Description.** Any non-cancellation exception in `ReadAsync` drops the reference to the dashboard's session. If the session did not fault (command timeout, non-Ok protocol status on a bulk subscribe or read, transient `SessionNotReady`), it stays in the registry as Ready with a live x86 worker and up to 256 advised tags. Nothing references it, so the fault sweep does not apply and the unattached-grace sweep is off by default; it lives until the 30-minute lease expires. The next Browse poll opens a new session and worker.
**Failure scenario.** An operator has a Browse page open with watched tags. The worker answers a bulk read with a non-Ok protocol status, or a command times out, repeatedly. The page polls every 2 s (`BrowsePage.razor:603`); each failing poll opens a fresh session and leaks the previous one. Within minutes the registry reaches `MaxSessions` and `OpenSession` is refused for real gRPC clients (OtOpcUa, ScadaBridge) for up to 30 minutes, with dozens of orphan worker processes still pumping events.
**Suggested fix.** In the catch block, capture the session id before invalidating and call `CloseQuietlyAsync` on it (still under `_gate`). Consider not invalidating on per-command failures that leave the session Ready.
**Test idea.** Fake `ISessionManager` whose session throws `SessionManagerException` from `ReadBulkAsync`; call `ReadAsync` twice; assert `CloseSessionAsync` was called for the first session id and at most one session is open.
---
## DSH-003 — Snapshot tick runs every health check; a slow check stalls the tick
- **Severity:** Medium — **Category:** Performance — **Confidence:** Confirmed
- **Locations:**
- `Dashboard/DashboardSnapshotService.cs:193-194, 215-216` — both refreshes awaited before every `yield return GetSnapshot()`
- `Dashboard/DashboardSnapshotService.cs:230-265` — `RefreshGatewayStatusAsync` runs `HealthCheckService.CheckHealthAsync` with a 2 s bound (`:27`)
- `Diagnostics/GatewayHealthCheckExtensions.cs:21-39` — registered checks: SQLite open + `SELECT 1`, worker exe, Galaxy SQL `TestConnectionAsync`, sessions
- `Diagnostics/GalaxySqlHealthCheck.cs` — own timeout 5 s
- `Dashboard/Hubs/DashboardSnapshotHub.cs:52` — one more full evaluation per hub connect
**Description.** While any dashboard page or `/hubs/snapshot` client is open, each snapshot tick (default 1 s) performs a Galaxy SQL round trip and a SQLite connection open. The page feed and the hub publisher each run their own enumeration, so with both audiences present it is up to two evaluations per second (the zero-timeout gate only skips overlapping ones). The evaluation is inline in the tick, so the snapshot cadence is coupled to the slowest check.
**Failure scenario.** Galaxy SQL becomes slow or unreachable (connect takes more than 2 s). Each tick now blocks for the 2 s bound before yielding, so every dashboard page updates roughly every 3 s instead of every 1 s. Because the 2 s outer bound is shorter than the check's own 5 s timeout, the check never gets to report `Unhealthy`: the outer cancellation propagates out of `CheckHealthAsync` and the status is written as `Unknown` (`:255-259`), which hides the actual cause. In steady state the cost is a 1–2 Hz SQL ping against the Galaxy Repository server for as long as a browser tab is open.
**Suggested fix.** Decouple status from the tick: refresh on its own slower interval (for example 10–15 s, like `ApiKeySummaryRefreshInterval`) in a background task, and have the tick read the cached value. Make the outer bound at least the longest per-check timeout.
**Test idea.** Fake `HealthCheckService` that delays 5 s; drive `WatchSnapshotsAsync` with a fake `TimeProvider`; assert snapshots keep arriving at the configured interval and that the health service is invoked at most once per refresh interval.
---
## DSH-004 — Session-details event pump renders once per wake
- **Severity:** Medium — **Category:** Performance — **Confidence:** Confirmed (code); magnitude Plausible
- **Locations:** `Dashboard/Components/Pages/SessionDetailsPage.razor:363-408` (pump), `:143-153` (unkeyed row loop)
**Description.** `PumpEventsAsync` wakes on `WaitToReadAsync`, drains whatever is queued, and dispatches `StateHasChanged`. Draining coalesces only events that arrived during the previous render dispatch; there is no minimum interval between renders. New events are prepended with `AddFirst` and the rows have no `@key`, so every render diffs all 50 rows as changed.
**Failure scenario.** An operator opens the details page of a session delivering about 240 events/s (the rate recorded for vd03). The pump issues on the order of 100+ renders per second for that circuit, each a 50-row, 5-column diff serialized to the browser, on top of the 1 Hz snapshot render. Several operators on busy sessions multiply this. The server-side cost lands on the gateway process that is also running the event pipeline.
**Suggested fix.** Coalesce by time: after a batch is applied, wait a fixed interval (for example 250 ms) before the next read, or drive rendering from a `PeriodicTimer` that drains the channel. Add `@key="evt.WorkerSequence"` to the row.
**Test idea.** bUnit with a fake subscription: write 1,000 events over one simulated second; assert the component's render count stays below a small bound and the final 50 rows are the newest 50.
---
## DSH-005 — Late `/hubs/alarms` clients never get the active-alarm snapshot
- **Severity:** Medium — **Category:** Bug — **Confidence:** Confirmed
- **Locations:** `Dashboard/Hubs/AlarmsHub.cs:40-44`; `Dashboard/Hubs/AlarmsHubPublisher.cs:104-128`
**Description.** The publisher holds one monitor subscription for the process lifetime. The monitor primes that subscription with the active-alarm snapshot once, at subscribe time, and the publisher group-sends it to whoever is connected at that moment — normally nobody, since it starts with the host. `AlarmsHub.OnConnectedAsync` only joins the group; it sends no reset, snapshot, provider status or truncation status, and the hub exposes no method to request them.
**Failure scenario.** The gateway starts with 40 active alarms. Ten minutes later an external consumer connects to `/hubs/alarms`. It receives only subsequent transitions; the 40 standing alarms, the current provider-degraded state and the truncation flag never arrive unless the publisher happens to resubscribe. The client shows an empty or partial alarm list indefinitely.
**Suggested fix.** In `OnConnectedAsync`, send the caller a `ResetMessage` followed by the current snapshot and status frames (redacted by the same rule), built from `IGatewayAlarmService.CurrentAlarms` / state, before adding it to the group.
**Test idea.** Start the publisher against a fake alarm service with two active alarms, then connect a hub client; assert it receives a reset plus two `active_alarm` frames without any new transition being raised.
---
## DSH-006 — Auth lifetimes are not enforced on live connections
- **Severity:** Medium — **Category:** Bug (security) — **Confidence:** Confirmed (by absence; repo-wide search finds no `CloseOnAuthenticationExpiration` and no revalidating `AuthenticationStateProvider`)
- **Locations:**
- `Dashboard/HubTokenService.cs:48` — 5-minute lifetime, described as the bound on stale roles and tag grants
- `Dashboard/HubTokenAuthenticationHandler.cs:57-58` — ticket carries no expiry
- `Dashboard/DashboardServiceCollectionExtensions.cs:113-117` — `AddSignalR()` and `AddCascadingAuthenticationState()` with defaults
- `Dashboard/Hubs/EventsHub.cs:66` and `Dashboard/DashboardSessionAcl.cs:141-151` — ACL evaluated against `Context.User`, which is fixed at connect
- `Dashboard/Components/Pages/SessionDetailsPage.razor:287-290`, `SessionsPage.razor:184-187` — admin actions re-read the circuit's fixed authentication state
**Description.** The token and cookie lifetimes bound only the handshake. A WebSocket hub connection opened with a valid token keeps its principal for as long as the socket stays up, and each later `SubscribeSession` on it is decided from the role and tag claims frozen at connect. The "re-resolved on every subscribe" rule therefore re-resolves nothing on this seam after the first five minutes. Blazor circuits behave the same way: the authentication state is captured at circuit start and is never revalidated, and a circuit with an open tab issues no HTTP requests, so cookie expiry or sign-out elsewhere does not end it.
**Failure scenario.** (a) A user with a tag grant mints a hub token, opens `/hubs/events`, and keeps the socket open. Their LDAP group is removed and they sign out. Hours later the same connection calls `SubscribeSession` for a newly opened tagged session and is admitted on the stale tag claims. (b) An Administrator leaves a Sessions tab open, signs out in another tab (or is removed from the admin group). The open tab can still Close sessions, Kill workers and manage API keys, because `CanManage` sees the circuit's original Admin principal.
**Suggested fix.** Stamp `ExpiresUtc` on the hub-token ticket and set `CloseOnAuthenticationExpiration = true` for the hub endpoints, so token-authenticated connections must reconnect with a fresh token. For circuits, register a `RevalidatingServerAuthenticationStateProvider` that re-checks the cookie/session on an interval, or at minimum tracks sign-out.
**Test idea.** Integration test with a short token lifetime: connect to `/hubs/events`, advance past expiry, assert the connection is closed or that `SubscribeSession` is refused. bUnit: flip the authentication state to signed-out and assert `ConfirmPendingAsync` is denied.
---
## DSH-007 — Cancelled Browse read can leave untracked advises
- **Severity:** Low — **Category:** Bug — **Confidence:** Plausible
- **Locations:** `Dashboard/DashboardLiveDataService.cs:152-155` (subscribe, then track), `:179` (cancellation deliberately not caught); `Dashboard/Components/Pages/BrowsePage.razor:677, 709` (page token cancels in-flight reads on dispose)
**Description.** If the caller's token fires after the bulk subscribe command was sent to the worker but before `TrackSubscribed` runs, the tags are advised on the worker with no entry in `_subscribed`. The session is not invalidated on cancellation, so those advises are never unadvised and do not count against `MaxSubscribedTags`. A later read of the same tags subscribes them again.
**Failure scenario.** An operator adds several tags and navigates away from Browse while the first read is in flight. The shared dashboard worker keeps those items advised, and keeps emitting data-change events for them, for the life of the dashboard session. Repeating this grows the standing advise set past its documented cap.
**Suggested fix.** Run the subscribe-and-track step under a token that is not the caller's (or under `CancellationToken.None` with the existing command timeout), and only observe the caller's token before and after it.
**Test idea.** Fake session whose `SubscribeBulkAsync` completes the worker-side subscribe and then observes cancellation; cancel mid-call; assert a subsequent read does not re-subscribe, or that an unadvise was issued.
---
## DSH-008 — `NativeDialog` JS interop on every render after first use
- **Severity:** Low — **Category:** Performance — **Confidence:** Confirmed
- **Locations:** `Dashboard/Components/Shared/NativeDialog.razor:56-87`; hosts at `SessionsPage.razor:30`, `SessionDetailsPage.razor:64`, `WorkersPage.razor:30`, `ApiKeysPage.razor:43,54`
**Description.** `OnAfterRenderAsync` calls `close` whenever the dialog is not open and the JS module is loaded, and `update` whenever it is open, with no check that anything changed. The host pages re-render on every snapshot tick, and the dialog receives a `RenderFragment` and an `EventCallback`, so it re-renders with them.
**Failure scenario.** An Administrator opens and dismisses one confirm dialog on the Sessions page. From then on that tab makes one JS interop round trip per second for as long as it stays open; an open create-key dialog does the same with `update`.
**Suggested fix.** Track the last state sent to JS (`open`/`closed`, `IsBusy`, generation) and skip the interop call when it is unchanged.
**Test idea.** bUnit with a JS interop mock: open then close the dialog, re-render the parent ten times, assert no further `close` invocations.
---
## DSH-009 — `AlarmsHubPublisher` has no idle gate
- **Severity:** Low — **Category:** Performance — **Confidence:** Confirmed
- **Locations:** `Dashboard/Hubs/AlarmsHubPublisher.cs:104-128, 196-218`
**Description.** Unlike the snapshot publisher (connection counter) and the events broadcaster (viewer registry), the alarm publisher always holds a monitor subscription, deep-clones each transition or active-alarm message for redaction (the default), and performs a group send, even when no hub client is connected. Server-rendered pages do not use this hub, so in most deployments the group is permanently empty.
**Failure scenario.** A site with a chatty alarm provider and no external hub consumer pays a protobuf clone and a SignalR group send per alarm message, plus a full snapshot replay on every resubscribe, for output nobody receives.
**Suggested fix.** Count `AlarmsHub` connections and skip the clone and send when the count is zero. This combines naturally with DSH-005: once connections are primed individually, the publisher can stay unsubscribed while idle.
**Test idea.** Run the publisher with a fake feed and zero connections; assert no `SendAsync` on the hub context and no clone (the source message instance count is unchanged).
---
## DSH-010 — Alarms page recomputes and re-renders every 3 s regardless of change
- **Severity:** Low — **Category:** Performance — **Confidence:** Confirmed
- **Locations:** `Dashboard/Components/Pages/AlarmsPage.razor:406-423`; `Dashboard/DashboardLiveDataService.cs:196-198`; `Dashboard/DashboardAlarmView.cs` (`Filtered`, `Areas`)
**Description.** Each open Alarms page projects the whole `CurrentAlarms` set into new `DashboardActiveAlarm` objects every 3 s, replaces its list, and increments `_alarmGeneration` unconditionally. That invalidates the memoized filter and area views, so the filter, two-key sort and distinct-area pass rerun and the whole table re-renders even when no alarm changed. The work is per circuit.
**Failure scenario.** With a few thousand active alarms and several operators on the page, the gateway allocates and sorts the full set per viewer every 3 s and pushes a full-table diff each time, while the alarm state is static.
**Suggested fix.** Bump the generation only when the result differs (compare count plus a cheap per-alarm signature, or expose a change sequence from the alarm service and skip the poll when it has not advanced).
**Test idea.** Poll twice with an unchanged fake alarm set; assert `DashboardAlarmView.FilterComputations` stays at 1.
@@ -0,0 +1,246 @@
# Server Security / Configuration / Alarms — Bug and Performance Review
- **Scope:** `src/ZB.MOM.WW.MxGateway.Server/Security/`, `.../Configuration/`, `.../Alarms/` at HEAD `54367e74`.
- **Method:** read-only code reading; no tests were run and no source was modified. Paths below are relative to `src/ZB.MOM.WW.MxGateway.Server/` unless stated.
- **Confidence:** *Confirmed* = the defect follows directly from the cited code. *Plausible* = the code permits it but it depends on timing or on behaviour outside this scope (stated per finding).
| ID | Severity | Category | Confidence | Title |
|---|---|---|---|---|
| SEC-001 | High | Bug | Confirmed | gRPC failure-limiter partition includes the client's ephemeral port, so the per-peer layer resets on every new connection |
| SEC-002 | High | Bug | Confirmed | Aggregate throttle runs ahead of the verification cache, so an unauthenticated sprayer can deny a key to its legitimate holder |
| SEC-003 | Medium | Bug | Confirmed | Every successful RPC wipes the key's cross-peer aggregate, so an actively used key is never aggregate-throttled |
| SEC-004 | Medium | Bug | Confirmed | Revoking/deleting a key does not end its already-open server streams |
| SEC-005 | High | Bug | Confirmed | Alarm monitor restart drops the cache without telling feed subscribers; alarms cleared during the gap stay active forever downstream |
| SEC-006 | Medium | Bug | Plausible | Reconcile applies an older worker snapshot over newer live transitions (phantom Clear / phantom Raise for one reconcile interval) |
| SEC-007 | Medium | Bug | Plausible | An Acknowledge for an alarm not in the cache (ack after return-to-normal) is inserted as a phantom `ActiveAcked` alarm |
| SEC-008 | Medium | Performance | Confirmed | Watch-list refresh runs an uncached Galaxy SQL query and rebuilds a full fingerprint every reconcile interval, and inline in the event loop on failover |
| SEC-009 | Low | Bug | Confirmed | Reconcile repair misses a same-state re-raise and silently ignores a non-OK reconcile reply |
| SEC-010 | Low | Performance | Confirmed | Monitor restart uses a fixed 5 s backoff and launches a new worker process on every attempt |
| SEC-011 | Low | Bug | Confirmed | Options validation gaps: `Alarms:ReconcileIntervalSeconds` unvalidated; `Events:ReplayRetentionSeconds` has no upper bound |
| SEC-012 | Low | Performance | Confirmed | Auth hot path allocates ~8 objects and hashes the token on every RPC even on a cache hit |
| SEC-013 | Low | Bug | Plausible | Constraint JSON missing a list member deserializes to `null` lists (NRE per RPC, or a `null` browse scope) |
| SEC-014 | Low | Performance | Confirmed | Audit retention sweep is a non-sargable full scan in the auth SQLite file and blocks host startup |
---
## SEC-001 — Failure-limiter partition includes the ephemeral source port
- **Severity:** High · **Category:** Bug (security) · **Confidence:** Confirmed
- **Location:** `Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:174-179`; `Security/Authorization/ApiKeyFailureLimiter.cs:148-159, 404-409`; contrast `Security/Authorization/MetricsAuthorization.cs:66-68`.
**Description.** `ResolveThrottlePartition` passes `context.Peer` straight into `ApiKeyThrottlePartition`. In Grpc.AspNetCore that string is `ipv4:<address>:<port>` (the repo's own test fixtures use `ipv4:127.0.0.1:5000`), and the port is the client's ephemeral source port. The limiter uses the string verbatim as the partition key and as the `_peerKeyIds` key. The "address that produced the failures" is therefore really "the TCP connection that produced them". The `/metrics` handler does it correctly with `Connection.RemoteIpAddress` (no port), so the two auth surfaces disagree.
**Failure scenario.** An attacker sends 9 bad secrets for `mxgw_operator01_*`, closes the channel, opens a new one (new source port) and repeats. No `(peer, key id)` partition ever reaches `ApiKeyFailureLimit` (10). The per-address cap of 32 key-id partitions (`MaxKeyIdPartitionsPerPeer`) is equally per-connection. Junk-shaped tokens land on the peer-only fallback partition, which is also fresh per connection, so junk spraying is never throttled at all (no key id means no aggregate either). Each connection also mints a tracked partition, pushing the map to its cap and forcing the O(n) `EvictIfOverCapacity` scan on every recorded failure.
**Suggested fix.** Derive the partition from the remote IP only (`context.GetHttpContext().Connection.RemoteIpAddress`, or strip the trailing `:port` from `Peer`, handling the bracketed `ipv6:[..]:port` form). Share one helper with `MetricsAuthenticationHandler`.
**Test idea.** Interceptor test: 9 failures from `ipv4:203.0.113.7:40001`, then 9 from `ipv4:203.0.113.7:40002`; assert the 11th failure overall is `ResourceExhausted`. Today it is `Unauthenticated`.
---
## SEC-002 — Aggregate throttle can deny a key to its legitimate holder
- **Severity:** High · **Category:** Bug (availability) · **Confidence:** Confirmed
- **Location:** `Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:125-143`; `Security/Authorization/ApiKeyFailureLimiter.cs:161-206, 307-325`.
**Description.** `failureLimiter.Check` runs before `apiKeyVerifier.VerifyAsync`, so it also runs before `CachingApiKeyVerifier`'s cache lookup. Once a key id's cross-peer aggregate is over `ApiKeyFailureAggregateLimit` (30 per 60 s), every request presenting that key id from any peer — including the legitimate holder, whose verification is already cached — is refused unless it wins the single probe slot per `ApiKeyFailureProbeIntervalSeconds` (5 s). The slot goes to whichever request arrives first, and a failed probe re-arms it (`RecordInto`, lines 319-323). Key ids are not secret (`docs/Authorization.md` line 99 says so).
**Failure scenario.** An attacker who knows key id `otopcua` sends bad secrets from three or more connections (see SEC-001; three source IPs also work). Thirty failures trip the aggregate. The attacker keeps sending at a high rate; the legitimate client at 50 RPC/s wins the 5-second probe only in proportion to its share of arrivals. When it does win, `Reset` clears the aggregate, and the attacker re-trips it within milliseconds. The legitimate client sees `ResourceExhausted` on nearly every call for as long as the spray continues. The class remark that the limiter "can never deny a key to the holder of the correct secret" does not hold.
**Suggested fix.** Let proven-good traffic bypass the valve: consult the verification cache before the limiter (a cache hit costs no store read, which is the only thing the limiter protects), and/or exempt a remote IP that has a recent successful verification for that key id from the aggregate layer. Keep the limiter in front of cache misses only.
**Test idea.** Prime a successful verification from `HolderPeer`; record 30 failures for the same key id from other peers; assert the holder's next call (inside the cache TTL and inside the probe interval) succeeds. Today it throws `ResourceExhausted`.
---
## SEC-003 — A successful RPC wipes the key's cross-peer aggregate
- **Severity:** Medium · **Category:** Bug (security) · **Confidence:** Confirmed
- **Location:** `Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:157`; `Security/Authorization/ApiKeyFailureLimiter.cs:275-281`.
**Description.** `Reset` runs on every successful authentication, cache hits included, and unconditionally does `_aggregates.TryRemove(partition.KeyId)`. For a key in steady use the aggregate is deleted many times per second, so it never accumulates.
**Failure scenario.** `otopcua` is polled at 20 RPC/s by its real client. A source-rotating sprayer (or a single host, given SEC-001) guesses secrets for the same key id. Each legitimate call deletes the aggregate before it reaches 30. The sprayer is bounded by neither layer, and every guess costs a SQLite read plus the peppered hash (failures are never cached). The aggregate layer only works for idle keys.
**Suggested fix.** On success, clear only the caller's own `(peer, key id)` partition. Leave the aggregate to decay by window, combined with the SEC-002 bypass so the holder is not penalised.
**Test idea.** Interleave one success per failure for the same key id from distinct peers; assert the aggregate still trips after 30 failures.
---
## SEC-004 — Revoke/delete does not end already-open streams
- **Severity:** Medium · **Category:** Bug (security) · **Confidence:** Confirmed
- **Location:** `Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:45-60`; `Security/Authentication/CachingApiKeyVerifier.cs:313-341`; call site `Dashboard/DashboardApiKeyManagementService.cs:105-109`.
**Description.** A server-streaming call is authenticated once, at open. Revoke/rotate/delete only evicts the verification cache. Nothing links an open `StreamEvents`, `StreamAlarms` or `WatchDeployEvents` call to its key id, and no code under `Sessions/`, `Grpc/` or `Alarms/` reacts to revocation.
**Failure scenario.** A key is leaked and an admin revokes it on the dashboard. The holder's open `StreamAlarms` stream (session-less, no lease) keeps delivering the galaxy-wide alarm feed, and an open `StreamEvents` keeps delivering tag values, until the client disconnects or the gateway restarts. New calls fail as expected, which makes the revoke look complete.
**Suggested fix.** Keep a per-key-id registry of `CancellationTokenSource`s for open streaming calls (registered in `ServerStreamingServerHandler`) and cancel them from `Invalidate(keyId)`. Optionally close sessions owned by the key.
**Test idea.** Open a streaming call through the interceptor with key K, call `Invalidate("K")`, assert the call's token is cancelled / the stream ends with `Unauthenticated`.
---
## SEC-005 — Monitor restart silently drops the cache; subscribers keep stale alarms
- **Severity:** High · **Category:** Bug · **Confidence:** Confirmed
- **Location:** `Alarms/GatewayAlarmMonitor.cs:330-342` (finally → `ClearCache`), `1007-1020`, `237-245`, `884-937`.
**Description.** `StreamAsync` subscribers deliberately outlive the monitor's worker session. When a lifecycle ends (worker crash, lease overflow, command failure) `ClearCache` empties `_alarms` with no `Clear` broadcast. After the restart the first `ApplyReconcile` diffs the new snapshot against the empty cache, so it emits only `Raise` repairs. An alarm that cleared while the monitor was down is in neither set and gets no `Clear`. Separately, the lifecycle start re-baselines `_providerMode/_providerDegraded/_providerReason` (lines 237-245) without `BroadcastToAll`.
**Failure scenario.** OtOpcUa holds a `StreamAlarms` stream. Alarm `Galaxy!Area.Tank01.HiHi` is active. The worker faults; the monitor restarts after 5 s plus worker startup. The alarm returns to normal during that gap. The new reconcile does not contain it, the cache is already empty, and no `Clear` is ever sent. OtOpcUa shows the alarm active until its own stream reconnects, which may be never. Likewise a subscriber that last saw `Subtag / degraded` keeps showing degraded after the restart lands back on the alarm manager, because Auto mode raises no mode-change event at start.
**Suggested fix.** Keep the previous generation for diffing instead of clearing it (hide it from `CurrentAlarms` while not `Monitoring`), so the first reconcile of the new lifecycle emits the missing `Clear`s. Alternatively broadcast `Clear` for every cached alarm in `ClearCache`. Broadcast the provider status after the re-baseline.
**Test idea.** Fake session manager: reconcile returns {A, B}; attach a subscriber; end the event stream to force a restart; second lifecycle's reconcile returns {A}. Assert the subscriber receives `Clear` for B. Second test: assert a `ProviderStatus` frame after a restart from Subtag.
---
## SEC-006 — Reconcile overwrites newer live state with an older snapshot
- **Severity:** Medium · **Category:** Bug · **Confidence:** Plausible (ordering race between two independent async paths; not reproduced)
- **Location:** `Alarms/GatewayAlarmMonitor.cs:413-467` (reconcile loop task), `293-311` (live loop), `884-947`.
**Description.** `ReconcileLoopAsync` runs concurrently with the live `await foreach`. `ApplyReconcile` replaces the cache with the worker's snapshot unconditionally. The snapshot reply and a later live transition travel different gateway paths (command-reply continuation versus pump → lease channel → loop). Nothing orders them, and `ApplyReconcile` compares no timestamp or sequence against the cached entry. The existing dedup only handles the reverse order (repair first, live duplicate second).
**Failure scenario.** The worker builds a snapshot without alarm X at t1 and raises X at t2. The live `Raise` is applied first (cache has X, feed sends Raise). The t1 snapshot is applied next: X is absent, so the monitor broadcasts a synthetic `Clear` and removes X. Subscribers and `QueryActiveAlarms` show a genuinely active alarm as cleared until the next pass (30 s by default). The mirror case — a snapshot containing X applied after the live `Clear` — re-raises a cleared alarm for one interval.
**Suggested fix.** In `ApplyReconcile`, skip any entry whose cached `LastTransitionTimestamp` is newer than the snapshot's, and skip a synthetic `Clear` for an entry inserted by a live transition after the reconcile command was issued (stamp entries with a monotonic apply counter captured before `InvokeAsync`). Or run the reconcile on the event loop.
**Test idea.** Drive `ApplyTransition(Raise X, ts=t2)` then `ApplyReconcile` with a snapshot lacking X captured "before"; assert no `Clear` is broadcast and X stays cached.
---
## SEC-007 — Acknowledge for an uncached alarm creates a phantom active alarm
- **Severity:** Medium · **Category:** Bug · **Confidence:** Plausible (depends on the worker emitting the transition; `Worker/MxAccess/AlarmRecordTransitionMapper.cs:88` maps `UnackRtn → AckRtn` to `Acknowledge`)
- **Location:** `Alarms/GatewayAlarmMonitor.cs:493-506`, `1284-1301`.
**Description.** The non-`Clear` branch of `ApplyTransition` always does `_alarms[reference] = SnapshotFromTransition(transition)`, and `SnapshotFromTransition` maps `Acknowledge` to `ActiveAcked` without checking that the alarm is cached as active.
**Failure scenario.** An alarm raises and returns to normal unacknowledged: `Clear` removes it from the cache. An operator then acknowledges the returned alarm; the worker emits `Acknowledge`. The monitor inserts it as `ActiveAcked`. `QueryActiveAlarms`, new `StreamAlarms` snapshots and the dashboard list an inactive alarm as active until the next reconcile, which then broadcasts a second, synthetic `Clear`. The same happens for any `Unspecified`/`Retrigger` kind, which fall through as `Active`.
**Suggested fix.** For `Acknowledge`, update the cache only when the reference is already present; still broadcast the transition. Ignore transition kinds other than Raise/Acknowledge/Clear for cache purposes.
**Test idea.** `ApplyTransition(Raise)`, `ApplyTransition(Clear)`, `ApplyTransition(Acknowledge)`; assert `CurrentAlarms` is empty.
---
## SEC-008 — Watch-list refresh: uncached SQL and full fingerprint every interval
- **Severity:** Medium · **Category:** Performance · **Confidence:** Confirmed
- **Location:** `Alarms/GatewayAlarmMonitor.cs:413-426, 558-562, 611-655, 692-725`; `Alarms/AlarmWatchListResolver.cs:59-141`; library `ZB.MOM.WW.GalaxyRepository/GalaxyRepository.cs:118-133` (new `SqlConnection` + query per call, no cache).
**Description.** With the defaults (`Fallback:Mode=Auto`, `Discovery:UseGalaxyRepository=true`) `CanUseSubtagFallback` is true, so every reconcile tick (30 s default, 5 s minimum):
1. runs the Galaxy alarm-attribute SQL query;
2. allocates one `AlarmSubtagTarget` plus four to six interpolated strings per alarm attribute;
3. builds, sorts and joins the canonical fingerprint string over every target.
The acknowledged fingerprint (one string covering the whole watch-list) is also retained for the process lifetime. For a galaxy with tens of thousands of alarm attributes that is several MB of large-object-heap garbage per tick, plus a steady load on the Galaxy SQL Server, to detect a change that only happens on deploy.
`ReconcileAsync` waits behind the refresh in the same pass, so a slow or hung Galaxy SQL stretches the reconcile cadence by the connect/command timeout. On a failover to Subtag the refresh is awaited inline in the event-consumer loop (line 560), stalling transition processing for the same duration at the moment the feed is degraded.
**Suggested fix.** Gate re-resolution on the deploy signal the gateway already tracks (last deploy time / hierarchy cache generation), or on a much longer interval. Store a SHA-256 of the fingerprint instead of the string. Run `ReconcileAsync` regardless of refresh latency (separate timers, or reconcile first). Bound the failover-edge refresh with a short timeout.
**Test idea.** Counting fake resolver: advance N reconcile ticks with an unchanged deploy time and assert `ResolveAsync` ran once. Resolver that delays 30 s: assert `QueryActiveAlarms` is still issued on schedule.
---
## SEC-009 — Reconcile misses a same-state re-raise; non-OK reconcile is silent
- **Severity:** Low · **Category:** Bug · **Confidence:** Confirmed
- **Location:** `Alarms/GatewayAlarmMonitor.cs:916-936`, `457-460`, `273-276`.
**Description.** (a) The repair delta compares `CurrentState` only. An alarm that cleared and re-raised between passes with both transitions missed, and is unacknowledged both times, has the same state and a new `OriginalRaiseTimestamp`; no `Raise` repair is emitted. The cache is updated, so `QueryActiveAlarms` and the live feed disagree on the instance. Severity and priority changes are dropped the same way. (b) `ReconcileAsync` returns without logging or setting `_lastError` when the worker replies non-OK. If that happens on the initial reconcile, the monitor still enters `Monitoring` with an empty cache.
**Failure scenario.** After a lease overflow window a consumer holds raise time T0 for an alarm whose current instance was raised at T1, and its "time in alarm" is wrong until the next real transition. A worker that rejects `QueryActiveAlarms` yields a healthy-looking monitor with zero alarms.
**Suggested fix.** Also treat a differing `OriginalRaiseTimestamp` as a `Raise` repair. Log a warning and surface `_lastError` on a non-OK reconcile; fail the lifecycle if the initial reconcile is non-OK.
**Test idea.** Two `ApplyReconcile` calls with the same reference and state but different `OriginalRaiseTimestamp`; assert a `Raise` is broadcast.
---
## SEC-010 — Fixed 5 s restart backoff launches a worker process per attempt
- **Severity:** Low · **Category:** Performance · **Confidence:** Confirmed
- **Location:** `Alarms/GatewayAlarmMonitor.cs:24, 171-198, 251-256, 398-405`.
**Description.** Any lifecycle failure restarts after a constant `RestartBackoff`. Each attempt calls `OpenSessionAsync`, which launches a new x86 worker with COM initialisation, before `SubscribeAlarms` can fail. A permanent failure (invalid subscription expression, alarm manager not installed, worker rejecting the command) therefore cycles a worker process roughly every 7 s indefinitely, and logs a warning with a stack trace each time.
**Failure scenario.** On a host under endpoint security that makes process launch expensive (the vd03 CPU investigation in `perf.md`), a misconfigured `Alarms:SubscriptionExpression` produces continuous process churn and log growth, and holds one of `MaxSessions` slots intermittently.
**Suggested fix.** Exponential backoff with a cap (for example 5 s → 5 min), reset after a lifecycle reaches `Monitoring`. Demote repeats of the same error to one summary line.
**Test idea.** Fake session manager whose `InvokeAsync` always rejects `SubscribeAlarms`; with a fake clock assert the gap between `OpenSessionAsync` calls grows.
---
## SEC-011 — Options validation gaps
- **Severity:** Low · **Category:** Bug · **Confidence:** Confirmed (missing checks); the downstream throws follow from `PeriodicTimer` / `TimeSpan` argument limits
- **Location:** `Configuration/GatewayOptionsValidator.cs:581-630` (no `ReconcileIntervalSeconds` check), `465-467`; `Alarms/GatewayAlarmMonitor.cs:415-439`; `Sessions/SessionEventDistributor.cs:303`.
**Description.**
- `Alarms:ReconcileIntervalSeconds` is never validated. Zero or negative values are silently clamped to 5. A value above about 4,294,967 s exceeds `PeriodicTimer`'s maximum period and throws `ArgumentOutOfRangeException` inside `ReconcileLoopAsync`, whose outer `try` catches only `OperationCanceledException`. The loop task faults unobserved (it is awaited only in a `finally` with an empty `catch`), so reconciliation never runs and nothing is logged.
- `Events:ReplayRetentionSeconds` (a `double`) is only checked `>= 0`. `Infinity` or anything above about 9.2e11 passes startup validation and then throws `OverflowException` from `TimeSpan.FromSeconds` when the first event distributor is built, so every `StreamEvents` fails at runtime rather than at startup.
**Failure scenario.** An operator sets `ReconcileIntervalSeconds` to a huge number meaning "effectively off". The monitor reports `Monitoring`, but missed transitions are never repaired and the watch-list is never refreshed.
**Suggested fix.** Validate `ReconcileIntervalSeconds` to a sane range (for example 5–86,400) and `ReplayRetentionSeconds` to finite and at most a day or so. Catch and log non-cancellation exceptions in `ReconcileLoopAsync`.
**Test idea.** Validator tests for both bounds; a monitor test asserting a faulted reconcile loop is logged.
---
## SEC-012 — Per-RPC allocations and hashing on the auth cache-hit path
- **Severity:** Low · **Category:** Performance · **Confidence:** Confirmed
- **Location:** `Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:125-159, 238`; `Security/Authorization/ApiKeyFailureLimiter.cs:305, 418`; `Security/Authentication/CachingApiKeyVerifier.cs:426-448`; `Security/Authentication/GatewayApiKeyIdentityMapper.cs:110-117`.
**Description.** A fully cached, successful RPC still performs:
- `TryResolveKeyId`: a new key-id string;
- `Composite(peer, keyId)`: a new concatenated string for a dictionary lookup that normally misses;
- `TryComputeCacheKey`: `token.ToString()`, a UTF-8 byte array, a SHA-256 over the token, a 64-character hex string, and a prefix concatenation;
- `ToGatewayIdentity`: a new `ApiKeyIdentity` record;
- `Reset`: two `TryRemove` calls.
That is about eight allocations (roughly 0.7 KB) plus a hash per call. It is small per call but sits on every unary RPC of the bulk-read path.
**Suggested fix.** Hash straight from the header span into a stack buffer and key the cache on a struct (or use an alternate span lookup). Cache the mapped gateway `ApiKeyIdentity` alongside the verification instead of re-mapping. Skip `Composite` when `_partitions` is empty. Skip `Reset` when `Check` found no tracked state.
**Test idea.** BenchmarkDotNet or an allocation assertion (`GC.GetAllocatedBytesForCurrentThread`) around `UnaryServerHandler` with a warm cache.
---
## SEC-013 — Partial constraint JSON yields `null` lists
- **Severity:** Low · **Category:** Bug · **Confidence:** Plausible (needs a blob not written by `ApiKeyConstraintSerializer.Serialize`, e.g. a hand-edited row or one written by another tool)
- **Location:** `Security/Authentication/ApiKeyConstraintSerializer.cs:30-38`; `Security/Authentication/ApiKeyConstraints.cs:3-11, 62-84`; `Security/Authorization/GatewayBrowseScopeProvider.cs:41-44`.
**Description.** `ApiKeyConstraints` is a positional record of non-nullable lists, but `JsonSerializer.Deserialize` leaves any constructor parameter that is absent from the JSON as `null`. Only `DashboardTags` normalizes null. `HasReadConstraints`, `HasWriteConstraints` and `IsEmpty` then dereference null. `GatewayBrowseScopeProvider` returns `BrowseSubtrees` as-is, and its return type is nullable in the library contract, so a missing `browse_subtrees` yields `null` rather than an empty list; how the library treats `null` was not verified here.
**Failure scenario.** A row whose constraints are `{"read_subtrees":["Area1*"]}` authenticates, then every constrained command throws `NullReferenceException` (surfacing as an internal error) when `ReadTagGlobs.Count` is evaluated.
**Suggested fix.** Normalize every list to `Array.Empty<string>()` after deserialization (or in the record's init accessors) and add a round-trip test for a sparse blob.
**Test idea.** `Deserialize("{\"read_subtrees\":[\"A*\"]}")`; assert every list is non-null and `HasWriteConstraints` does not throw.
---
## SEC-014 — Audit retention sweep is a full scan in the auth database
- **Severity:** Low · **Category:** Performance · **Confidence:** Confirmed
- **Location:** `Security/Audit/SqliteCanonicalAuditStore.cs:43-57, 158-176`; `Security/Audit/AuditDrainService.cs:43-60`.
**Description.** `DELETE FROM audit_event WHERE datetime(occurred_at_utc) < datetime($cutoff)` wraps the column in a function, and the table has no index on `occurred_at_utc`. The primary key is a random GUID stored as text. Each sweep (hourly, and once in `StartAsync` before the host continues starting) scans the whole table and holds SQLite's single write lock for the duration, in the same file the API-key store reads and the `last_used` write uses.
**Failure scenario.** A deployment with a constraint-denied-heavy client accumulates millions of audit rows over the 90-day retention. Startup blocks on the scan, and an hourly write-lock pause delays `MarkUsed` and admin writes.
**Suggested fix.** The stored value is already a fixed-width ISO-8601 UTC string, so compare it directly (`occurred_at_utc < $cutoff`) and add an index on `occurred_at_utc`. Delete in bounded chunks. Run the startup sweep from the background loop instead of `StartAsync`.
**Test idea.** `EXPLAIN QUERY PLAN` assertion that the delete uses the index; a startup test with a slow sink asserting `StartAsync` does not await the sweep.
@@ -0,0 +1,300 @@
# Server Sessions + gRPC: Bugs and Performance Review
- **Date:** 2026-12-02
- **HEAD:** `54367e74`
- **Scope:** `src/ZB.MOM.WW.MxGateway.Server/Sessions/`, `src/ZB.MOM.WW.MxGateway.Server/Grpc/`, plus `Program.cs` / `GatewayApplication.cs` where they affect those.
- **Method:** read-only code reading. One finding (SES-001) was also checked with a throwaway minimal host outside the repo. Nothing in the repo was built, run or modified.
Paths below are relative to `src/ZB.MOM.WW.MxGateway.Server/` unless they start with `src/` or `docs/`.
## Summary
| ID | Severity | Category | Confidence | Title |
|---|---|---|---|---|
| SES-001 | High | Bug | Confirmed | Host stop waits 30 s on open streams, then kills every worker instead of closing gracefully |
| SES-002 | High | Bug | Confirmed | `Invoke` and `CloseSession` are not owner-scoped; `DrainEvents` bypasses the `StreamEvents` owner check |
| SES-003 | High | Bug | Confirmed | `AddBufferedItem` skips the API-key read-constraint check |
| SES-004 | Medium | Bug | Confirmed | An expired lease closes a detached session before `DetachGraceSeconds` elapses |
| SES-005 | Medium | Bug | Plausible | A half-open client connection pins the session and blocks the owner's reconnect (no HTTP/2 keepalive) |
| SES-006 | Low | Bug | Confirmed | A resume cursor ahead of the stream silently drops every live event up to that cursor |
| SES-007 | Low | Bug | Confirmed | `Unregister` never purges the session's item registrations |
| SES-008 | Low | Performance | Confirmed | A sparse `Time` array write allocates one `Timestamp` per slot before any size or readiness check |
The distributor (`SessionEventDistributor`), the replay/live handoff, the close gate and the sweep reservation were read closely for races, lock inversion and off-by-one errors. I found nothing reportable there beyond SES-006.
---
## SES-001: Host stop waits 30 s on open streams, then kills every worker
- **Severity:** High
- **Category:** Bug
- **Confidence:** Confirmed (host ordering reproduced on .NET 10 with a minimal app; the gateway consequence follows from the code)
- **Locations:**
- `Sessions/SessionServiceCollectionExtensions.cs` (`AddHostedService<SessionShutdownHostedService>`)
- `Sessions/SessionShutdownHostedService.cs:29-39`
- `Sessions/SessionManager.cs:113` (the `ApplicationStopping` hook only sets a flag), `:498-582`
- `Sessions/GatewaySession.cs:1867` (`_closeLock.WaitAsync(cancellationToken)`)
- `Program.cs` (`app.Run()`), `GatewayApplication.cs:41-57`
- `docs/Grpc.md:327`, `docs/Sessions.md:397` (describe the opposite order)
### Description
The session drain runs from `SessionShutdownHostedService.StopAsync`. With `WebApplication`, Kestrel's own hosted service is registered last, so it stops first. Kestrel's stop waits for in-flight requests, and an open `StreamEvents` call is an in-flight request that only ends when its session closes. Nothing ends it at `ApplicationStopping`: `SessionManager.MarkStopping` only blocks new opens.
So the sequence on any stop with at least one active stream is:
1. Kestrel waits the full host shutdown timeout (30 s by default; the repo sets no `HostOptions.ShutdownTimeout`).
2. Kestrel aborts the connections. The streams end with a transport abort, not the clean `OK` that `docs/Grpc.md:327` describes.
3. `SessionShutdownHostedService.StopAsync` is then called with a token that is already cancelled.
4. `ShutdownAsync` passes that token to `CloseSessionCoreAsync`. `GatewaySession.CloseAsync` throws at `_closeLock.WaitAsync(cancellationToken)` before the worker is asked to shut down.
5. Every session falls to the kill fallback (`SessionManager.cs:548-570`), logging one "Graceful shutdown failed" warning per session.
### Evidence
A minimal .NET 10 `WebApplication` with one `IHostedService` and one open streaming request printed:
```
ApplicationStopping
stream ABORTED at 30.0s
Drain.StopAsync at 30.0s tokenCancelled=True
```
With no open request, the same hosted service's `StopAsync` ran at 0.0 s with a live token.
### Failure scenario
OtOpcUa or ScadaBridge holds a `StreamEvents` stream (the normal production state). An operator stops the `MxAccessGw` service for a deploy. The stop hangs 30 s, every x86 worker is killed with no MXAccess `Unregister`/`UnAdvise` cleanup, and clients see an aborted stream. If the service wrapper's own stop timeout is shorter than 30 s, the gateway is terminated first and the workers are left to the orphan terminator on the next start.
### Suggested fix
Start the drain from `IHostApplicationLifetime.ApplicationStopping` (for example, have `MarkStopping` kick off `ShutdownAsync` once and let `SessionShutdownHostedService.StopAsync` await that same task). Closing the sessions completes the subscriber channels, so the streams end with `OK` and Kestrel drains at once. Then correct `docs/Grpc.md` and `docs/Sessions.md`.
### Test idea
A Kestrel-backed (not `TestServer`) integration test: open a session on the fake worker, start `StreamEvents`, call `StopAsync` on the host. Assert the stop finishes well under the shutdown timeout, the stream ends with `OK`, and the fake worker saw a graceful shutdown (`ShutdownCount == 1`, `KillCount == 0`).
---
## SES-002: `Invoke` and `CloseSession` are not owner-scoped; `DrainEvents` bypasses the stream owner check
- **Severity:** High
- **Category:** Bug (authorization)
- **Confidence:** Confirmed
- **Locations:**
- `Grpc/EventStreamService.cs:58` (the only use of `OwnerKeyId` in the server)
- `Grpc/MxAccessGatewayService.cs:79-101` (`CloseSession`), `:104-174` (`Invoke`), `:326-336` (`ResolveSession`)
- `Security/Authorization/GatewayGrpcScopeResolver.cs:52` (`DrainEvents` needs only `events:read`)
- `src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSession.cs:615`, `:997-1037` (`DrainEvents` dequeues from the same queue the event pump drains)
- `docs/DesignDecisions.md:88-97`, `docs/Sessions.md:277`
### Description
`StreamEvents` rejects a caller whose key id differs from `GatewaySession.OwnerKeyId`. `Invoke` and `CloseSession` resolve the session by id and never compare the owner. The design decision says an `events:read` key that learns a session id must not receive another key's events. `Invoke(DrainEvents)` does exactly that: it requires `events:read`, returns the session's queued events in the reply, and removes them from the worker queue.
The same gap lets a foreign key with the matching scope:
- close another key's session (`session:close`);
- add, advise and write through it (`invoke:read` / `invoke:write`), with events delivered to the owner's stream;
- read worker and session state.
Session ids are random, but they appear on the dashboard Sessions pages (visible to Viewers, and to anonymous localhost by default) and in logs.
### Failure scenario
Key A opens `session-…abc` and streams. Key B (scope `events:read`, different tenant) calls `Invoke` with `DRAIN_EVENTS` on that id in a loop. B receives A's data-change events, including tags outside B's read constraints. A's stream silently misses those events: they never reach the gateway pump, so the replay ring has no record and no `ReplayGap` is raised.
### Suggested fix
Apply the same ordinal owner comparison in `Invoke` and `CloseSession` (one helper next to `ResolveSession`), returning `PermissionDenied`. Decide explicitly whether an `admin`-scoped key may override. Internal callers (`GatewayAlarmMonitor`, dashboard) go through `ISessionManager` directly and are unaffected.
### Test idea
Open a session as key A. As key B, call `Invoke(DrainEvents)`, `Invoke(Write)` and `CloseSession` on A's session id. Assert `PermissionDenied` for each and that A's session is still `Ready`.
---
## SES-003: `AddBufferedItem` skips the API-key read-constraint check
- **Severity:** High
- **Category:** Bug (authorization)
- **Confidence:** Confirmed
- **Locations:**
- `Grpc/MxAccessGatewayService.cs:338-483` (`ApplyConstraintsAsync`: cases for `AddItem` at `:347` and `AddItem2` at `:351`, none for `AddBufferedItem`)
- `Sessions/GatewaySession.cs:1420-1421`, `:1535-1541` (the session does treat `AddBufferedItem` as an add elsewhere)
### Description
Read constraints are enforced when an item is added: `AddItem`, `AddItem2`, `AddItemBulk`, `SubscribeBulk` and `ReadBulk` all call `CheckReadTagAsync`. Single `Advise` is not checked, because it relies on the add having been checked. `AddBufferedItem` carries an `item_definition` like the other adds but falls into `default: return null`, so it reaches the worker unchecked.
### Failure scenario
A key is restricted to the read subtree `AreaA`. It calls `AddBufferedItem(server, "AreaB.Tank.Level")`, which succeeds, then `Advise` on the returned handle. Data for `AreaB.Tank.Level` arrives on its event stream. No denial is audited.
### Suggested fix
Add an `AddBufferedItem` case that calls `EnforceReadTagAsync` with `command.AddBufferedItem.ItemDefinition`. Consider making the switch fail closed for any command kind that carries a tag address.
### Test idea
In the `MxAccessGatewayService` constraint tests, send `AddBufferedItem` for a tag outside the key's read scope. Assert `PermissionDenied`, a recorded denial, and that the worker received no command.
---
## SES-004: An expired lease closes a detached session before `DetachGraceSeconds` elapses
- **Severity:** Medium
- **Category:** Bug
- **Confidence:** Confirmed
- **Locations:**
- `Sessions/GatewaySession.cs:1135-1142` (`TouchClientActivity`; called only at `:1054` and `:1396`)
- `Sessions/GatewaySession.cs:1149-1157` (`IsLeaseExpired`), `:2016-2019`
- `Sessions/GatewaySession.cs:2485-2521` (`DetachEventSubscriber` stamps `_detachedAtUtc` but does not move the lease)
- `Sessions/SessionManager.cs:421-429` (lease expiry is checked first)
### Description
The lease moves only on a unary command. While a subscriber is attached, `IsLeaseExpired` is held false by `_activeEventSubscriberCount > 0`, but `_leaseExpiresAt` keeps ageing. A client that streams for longer than `DefaultLeaseSeconds` (1800 s) without a unary call has a lease that is already in the past. The moment its stream drops, the session is lease-expired, and the next sweep closes it with `lease-expired` regardless of the detach-grace window.
### Failure scenario
A driver opens a session, subscribes, then only streams for hours. A network blip drops the stream. Expected: the session is retained for at least 30 s so the client can resume with replay. Actual: the session survives only until the next sweep tick, which is 0 to 30 s away with the default `LeaseSweepIntervalSeconds`. A reconnect that lands after that tick gets `SessionNotFound` and must rebuild every subscription. A larger configured `DetachGraceSeconds` has no effect at all for such a session.
### Suggested fix
In `DetachEventSubscriber`, when the last external subscriber drops, extend the lease to at least `now + _detachGrace` (or simply call the lease refresh with `now`). Streaming is client activity; the detach is the last moment of it.
### Test idea
With a fake `TimeProvider`: open, attach, advance 31 minutes with no commands, dispose the lease, advance 5 s, run `CloseExpiredLeasesAsync`. Assert the session is still registered. Advance past `DetachGraceSeconds` and assert it closes with `detach-grace-expired`.
---
## SES-005: A half-open client connection pins the session and blocks the owner's reconnect
- **Severity:** Medium
- **Category:** Bug (resource leak / reconnect)
- **Confidence:** Plausible (the missing keepalive and the attach rules are confirmed in code; not reproduced against a dropped connection)
- **Locations:**
- `GatewayApplication.cs:276` (the only `ConfigureKestrel` call; sets the TLS certificate only)
- `Security/Authorization/GrpcAuthorizationServiceCollectionExtensions.cs:36-39` (gRPC options; no keepalive)
- `Sessions/GatewaySession.cs:1262-1271` (second attach refused in single-subscriber mode)
- `Sessions/GatewaySession.cs:1149-1157`, `:2021-2025`, `:2040-2054` (every sweep rule requires zero active subscribers)
### Description
Kestrel's HTTP/2 keepalive ping is off unless configured, and the repo does not configure it. If a client vanishes without a FIN or RST (host power loss, firewall or NAT idle drop, cable pull), the server learns of it only when a write eventually times out at the TCP layer. On a session with no event traffic, no write happens, so the `StreamEvents` call never ends.
While that dead stream is attached:
- `_activeEventSubscriberCount` stays at 1, so lease expiry, detach-grace and unattached-grace never fire. The session and its x86 worker are held indefinitely and count against `MaxSessions` (64).
- In the default single-subscriber mode, the real client's resume is refused with `EventSubscriberAlreadyActive` (`ResourceExhausted`) because its own dead stream still holds the slot.
### Failure scenario
A plant firewall drops an idle gRPC connection on a quiet session (slow-changing setpoints). The client notices on its side and calls `StreamEvents` with its resume cursor. The gateway answers `ResourceExhausted` on every retry until some event is written and the TCP retransmits give up, which on a quiet session may be hours. Clients that fall back to opening a new session leave the old one and its worker running.
### Suggested fix
Set `Limits.Http2.KeepAlivePingDelay` and `KeepAlivePingTimeout` in `ConfigureKestrel` (for example 30 s / 20 s), exposed as options. Optionally, let a resume by the owning key displace the existing subscriber in single-subscriber mode.
### Test idea
Kestrel-backed test with a raw HTTP/2 client that opens `StreamEvents` and then stops reading and stops answering pings. Assert the server call token fires within ping delay plus timeout and `ActiveEventSubscriberCount` returns to 0.
---
## SES-006: A resume cursor ahead of the stream silently drops live events
- **Severity:** Low
- **Category:** Bug
- **Confidence:** Confirmed (behaviour); the trigger needs a client that sends a wrong cursor
- **Locations:**
- `Sessions/SessionEventDistributor.cs:531-570` (`highestReplayed` starts at `afterSequence`; gap is only raised when the caller is behind)
- `Grpc/EventStreamService.cs:102`, `:230`
### Description
`RegisterWithReplay` never compares `afterSequence` with `_highestSequenceSeen`. If the cursor is higher than anything the session has produced, nothing is replayed, no gap is reported, and `LiveResumeSequence` is the caller's value. The live loop then discards every event with `worker_sequence <= afterSequence`.
### Failure scenario
A client reuses a cursor of 50,000 from an earlier session on a new session whose worker sequence restarts at 1. The stream attaches successfully and delivers nothing until the new session has produced 50,000 events. Neither side logs or signals anything. (The bundled .NET client keeps its cursor per session object, so this needs a third-party or hand-rolled client.)
### Suggested fix
When `_anyEventSeen` is false or `afterSequence > _highestSequenceSeen`, either reject the attach with `InvalidArgument` or clamp `liveResumeSequence` to `_highestSequenceSeen` and emit the `ReplayGap` sentinel so the client re-snapshots.
### Test idea
Feed sequences 1..10, call `RegisterWithReplay(afterSequence: 1000)`, then feed 11..20. Assert the subscriber either fails to attach or receives 11..20 with a gap signal.
---
## SES-007: `Unregister` never purges the session's item registrations
- **Severity:** Low
- **Category:** Bug (unbounded growth, stale constraint data)
- **Confidence:** Confirmed (no purge); the stale-mapping consequence is Plausible
- **Locations:**
- `Sessions/GatewaySession.cs:69` (`_items`)
- `Sessions/GatewaySession.cs:1520-1561` (`TrackCommandReply`: removal only for `RemoveItem`, `RemoveItemBulk`, `UnsubscribeBulk`)
### Description
`_items` maps `(ServerHandle, ItemHandle)` to a tag address and is what `CheckReadHandleAsync` / `CheckWriteHandleAsync` consult. A successful `Unregister` invalidates every item under that server handle in MXAccess, but the gateway keeps the entries for the life of the session.
Tracking is also skipped whenever the caller cancels after the command was dispatched (`MxAccessGatewayService.cs:138-167`): the worker still executes the `RemoveItem`, and the entry stays.
### Failure scenario
A long-lived session whose client re-registers on each of its own reconnect cycles (`Register`, bulk add of 20,000 tags, `Unregister`, repeat) grows `_items` by 20,000 entries per cycle. If MXAccess hands out the same handle values again, a stale entry describes a different tag than the handle now refers to until the next add overwrites it, and the write-constraint check reads that stale address.
### Suggested fix
On a successful `Unregister`, remove every `_items` entry whose `ServerHandle` matches.
### Test idea
Track three items under server handle 1, call `TrackCommandReply` with a successful `Unregister` for handle 1, assert `TryGetItemRegistration` returns false for all three.
---
## SES-008: Sparse `Time` array write allocates one `Timestamp` per slot before any check
- **Severity:** Low
- **Category:** Performance
- **Confidence:** Confirmed
- **Locations:**
- `Sessions/SparseArrayExpander.cs:228-246` (`new Timestamp` per element)
- `Sessions/GatewaySession.cs:1390-1395` (expansion runs before `GetReadyWorkerClientAsync` and before the worker-frame size pre-check)
- `Configuration/EventOptions.cs:54` (`MaxSparseArrayLength = 1_000_000`)
### Description
For `MxDataType.Time`, the expander fills the array with a fresh `Timestamp` object per slot. A request of a few dozen bytes (`total_length = 1_000_000`, one element) makes the gateway allocate a million objects plus the backing array, then serialise a multi-megabyte frame, before it checks whether the session is ready or whether the frame fits `MaxMessageBytes`. The other element types fill with value types or a shared empty string and are much cheaper.
### Failure scenario
A key with `invoke:write` sends such writes in a tight loop, including against a session that is not `Ready`. Each call costs roughly 30 MB of short-lived allocations and pushes the gateway into frequent gen-2 collections, which shows up as latency on every session's event relay.
### Suggested fix
Run the readiness check before `NormalizeOutboundCommand`, and bound the expanded size against the frame limit before filling. For `Time`, fill unspecified slots with one shared default `Timestamp` instance (the expanded array is serialised once and not mutated).
### Test idea
Benchmark or allocation test: expand a `Time` sparse value with `total_length = 1_000_000` and one element; assert allocated bytes stay under a fixed budget. Separately assert a sparse write to a non-`Ready` session fails without expanding.
---
## Known items from `perf.md` still present in code
Not re-reported as findings; listed so the status is visible.
| `perf.md` item | Still in code at |
|---|---|
| Dashboard mirror attached eagerly at `MarkReady`, woken per event | `Sessions/GatewaySession.cs:656`, `:851-931`, `:942-988` |
| Send-latency histogram recorded on every gRPC write | `Grpc/MxAccessGatewayService.cs:194-201` |
| `CalculateSize()` and two `GetUtcNow()` calls per replay append | `Sessions/SessionEventDistributor.cs:965-966`, `:1002` |
| No `BufferHint` batching of gRPC writes | `Grpc/MxAccessGatewayService.cs:198` |
| Subscriber channels use `AllowSynchronousContinuations = false` (one pool hop per event per subscriber) | `Sessions/SessionEventDistributor.cs:414-422` |
@@ -0,0 +1,203 @@
# 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.
@@ -0,0 +1,245 @@
# 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:
1. `LastActivityUtc` freezes even though the STA is doing useful work.
2. Queued `InvokeAsync` work items do not run. `commandWakeEvent` is signalled but nothing looks at the queue. This includes the alarm poll and any `UnAdvise`/`RemoveItem` a 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 `WriteFile` per frame (`WorkerFrameWriter.cs:780`).
- Each pass then calls `FlushAsync` (`WorkerFrameWriter.cs:643`, plus `:591` on a control-to-event transition). On .NET Framework 4.8 `PipeStream` does not override `FlushAsync`, so this is a `Task.Factory.StartNew` hop around a `Flush` that 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 at `WorkerPipeSession.cs:18-22` says an idle worker "parks instead of waking 40x/s"; the code does not do that.
- There is no record-info pin, so `lmxproxy` still 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`; callers `MxAccess/MxAccessEventMapper.cs:274-280`, `:339`, `:512-516`; fault path `MxAccess/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:
- `FormatException` for a string element. MXAccess delivers the `OnDataChange` timestamp as a `VT_BSTR` (`MxAccessEventMapper.cs:346-351`), so a VARIANT array of BSTR timestamps is a credible shape for `OnBufferedDataChange`.
- `ArgumentOutOfRangeException` for a negative or oversized `long`, in the array path and in the scalar paths at `:369` and `:392`.
- A wrong value, with no exception, for a `double` element (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 sites `Conversion/VariantConverter.cs:178-181`, `:260-263`; call sites `MxAccess/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:
1. The first `_reader.ReadAsync` waits for `GatewayHello` with no timeout, and net48 pipe reads ignore the token. A peer that connects and never sends keeps the worker alive indefinitely.
2. After the hello is read, no read is outstanding while `initializeMxAccessAsync` runs. If COM activation hangs on the STA and the gateway dies or abandons the launch, nothing in the worker notices. `WorkerApplication.Run` passes 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 to `EndOfStream`, single-consumer invariant holds through teardown.
- **STA wake handoff** (`Sta/StaRuntime.cs`): the `AutoResetEvent` stays signalled if set between the last dequeue and the wait, so no wakeup is lost. Enqueue and the shutdown/fault flags share `gate`, so no item is enqueued after the final cancel sweep.
- **`StaWorkItem`**: cancel-versus-execute is settled by one `CompareExchange`; 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`): the `nonce` field logged at `WorkerApplication.cs:152` is redacted by field name.
@@ -0,0 +1,232 @@
# 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 `UnAdvise`s and `RemoveItem`s 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.