diff --git a/code-reviews/2026-12-02-perf-bugs/PLAN.md b/code-reviews/2026-12-02-perf-bugs/PLAN.md index 315f6e51..c6e72094 100644 --- a/code-reviews/2026-12-02-perf-bugs/PLAN.md +++ b/code-reviews/2026-12-02-perf-bugs/PLAN.md @@ -2,7 +2,24 @@ 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-`) 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. During each task run only the targeted tests (`--filter`), and run the full gateway suite once at the end of the phase. +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. --- @@ -12,9 +29,9 @@ These are real trust-boundary gaps. The SES-002, SES-003 and DSH-001 code paths | # | 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.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`. Check `/admin/secrets` (Secrets.Ui) under the same path. | bUnit or integration test: anonymous-localhost principal navigating in-circuit to `/alarms` gets NotAuthorized. | +| 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. | @@ -31,12 +48,11 @@ MXA-002 / WIP-002 / MXA-006. The fixes are already written, tested on windev, an 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. +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 -Mode test`) and the gateway suite. -3. Merge to `main`, then follow the rollout plan committed on the branch (`3be20983`) for QA and PROD. +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. -Close `perf.md` by moving it into `docs/` (or deleting it, since it is untracked) once the work is merged. --- @@ -47,7 +63,7 @@ Close `perf.md` by moving it into `docs/` (or deleting it, since it is untracked | 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.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. | @@ -85,9 +101,9 @@ All worker-side (net48 x86, so no init-only props or records). MXAccess parity i |---|---|---| | 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.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 | Null array elements map to an explicit null/empty representation, not 0 / `false` / epoch. Decide against observed MXAccess behaviour first. | +| 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. @@ -119,7 +135,7 @@ Each item is applied to every affected client in one change, so the five clients | # | 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.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. | @@ -143,4 +159,4 @@ Each item is applied to every affected client in one change, so the five clients | 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. +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).