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

163 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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.
Tracking issues: phases #251–#257, and High findings #241–#250 (SES-002 #241, SES-003 #242, DSH-001 #243, SEC-001 #244, SEC-002 #245, WIP-001 #246, SES-001 #247, DSH-002 #248, MXA-001 #249, SEC-005 #250). MXA-002 / WIP-002 are tracked by the existing #235 / #236. Docs change in the same commit as the code.
## Decisions (2026-12-03)
The user accepted all ten recommended answers. They are folded into the phase sections below.
| # | Question | Decision |
|---|---|---|
| D1 | Where the review commits go | Fast-forward `main` to the review branch. Push only on explicit go-ahead. |
| D2 | Admin override of the session-owner check (SES-002) | **No override.** `Invoke` and `CloseSession` use the same strict ordinal compare as `StreamEvents`. Operators close or kill any session through the dashboard, which calls `ISessionManager` directly. A gRPC override would be a separate, explicit, audited feature. |
| D3 | `/admin/secrets` exposure (DSH-001) | Verify it in the #243 fix with a test. If it was reachable, record that on #243 as a confirmed exposure. |
| D4 | How the perf branches land | Rebase `fix/readbulk-subscription-teardown` (which carries all three stacked branches) onto `main` and merge it as one unit, after windev worker CI. QA/PROD deploy is a separate step the user asks for. |
| D5 | #238 (closed, fix unmerged) | Reopened 2026-12-03. Close it when Phase 1 merges. |
| D6 | Untracked `perf.md` | Commit it as `docs/WorkerEventPathPerformance.md` in the Phase 1 merge, so the doc lands with the code it describes. |
| D7 | gRPC keepalive values | Clients ping every 30 s with a 10 s timeout, also while no call is active. The server permits pings at that rate and sends its own after 60 s idle. All values are configurable (`MxGateway:*`, client options). |
| D8 | Null array elements (WIP-008) | Live-capture on windev first. If MXAccess can't produce nulls in arrays, close WIP-008 as unreachable. Don't invent a null encoding. |
| D9 | Status for worker-side validation failures (WIP-005) | The existing `PROTOCOL_STATUS_CODE_INVALID_REQUEST` with no HRESULT, or `WORKER_UNAVAILABLE` during STA shutdown. Only real `COMException`s stay `MxaccessFailure`. No `.proto` change. |
| D10 | Issues for Medium/Low findings | None. They are tracked as rows in the phase issues (#251–#257). Open a separate issue only when a finding is split out, deferred, or grows. | 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) → #251
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 (#241) | 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`). No `admin` override (D2); record the owner rule for all session-scoped RPCs 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`, even when B holds `admin`; 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`. Covers `/admin/secrets` (Secrets.Ui) too (D3). | bUnit or integration test: in-circuit navigation by anonymous localhost to `/alarms` and by a Viewer to `/admin/secrets` both get NotAuthorized. If `/admin/secrets` was reachable before the fix, note it on #243. |
| 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) → #252
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, and merges as one unit (D4).
2. Run the windev worker CI (`windev-worker-ci.ps1 -Sha <sha> -Mode test`) and the gateway suite.
3. Merge to `main`, adding `perf.md` as `docs/WorkerEventPathPerformance.md` in the same merge (D6), and close #238 (D5). QA and PROD rollout follows the plan committed on the branch (`3be20983`), but only when the user asks for it.
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.
---
## Phase 2 — Session and worker lifecycle (p1) → #253
| # | 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 under `MxGateway:*` (D7: server pings after 60 s idle with a 10 s timeout, and permits client pings every 30 s including with no active call), 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) → #254
| # | 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) → #255
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 (`ArgumentException`) return the existing `INVALID_REQUEST` with no HRESULT, and STA shutdown returns `WORKER_UNAVAILABLE` (D9). Only `COMException`s stay `MxaccessFailure`. No `.proto` change, so clients are unaffected. |
| 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 | Live-capture on windev first (D8). If MXAccess can produce null array elements, match its observed representation; if it can't, close WIP-008 as unreachable with the capture as evidence. |
| 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) → #256
| # | 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) → #257
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 (D7): 30 s ping, 10 s timeout, also while no call is active, configurable in each client's 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. Medium and Low findings stay as rows in the phase issues; split one into its own issue only when it is deferred or grows (D10).