301 lines
19 KiB
Markdown
301 lines
19 KiB
Markdown
# 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` |
|