Commit Graph

370 Commits

Author SHA1 Message Date
Joseph Doherty f616a551d2 Merge fix/review-2026-12-phase2 (2026-12-02 review fix plan) 2026-12-03 10:18:43 -05:00
Joseph Doherty 8e720bc727 fix(worker): bound shutdown alarm steps by the grace; watchdog stands down while shutting down; startup handshake deadline (MXA-003, WIP-007, WIP-009, #253)
ci / windows-x86 (push) Failing after 11m18s
ci / java (push) Failing after 11m43s
ci / portable (push) Failing after 12m6s
2026-12-03 10:07:41 -05:00
Joseph Doherty a474d3219b fix(grpc): configure Kestrel HTTP/2 keepalive (60 s ping, 10 s timeout) under MxGateway:Protocol (SES-005, #253) 2026-12-03 10:03:53 -05:00
Joseph Doherty 87b8f8da09 fix(workers): orphan cleanup skips workers whose owning gateway is still running (WRK-009, #253) 2026-12-03 10:00:16 -05:00
Joseph Doherty 152a12cea9 fix(dashboard): enforce auth lifetimes on live hub connections and circuits (DSH-006)
Hub tokens and cookies bounded only the handshake: an open hub socket kept its
connect-time roles and tag grants indefinitely, and a Blazor circuit never
revisited its sign-in. The hub-token ticket now carries the token expiry and the
hubs are mapped with CloseOnAuthenticationExpiration. Circuits use
DashboardRevalidatingAuthenticationStateProvider, which signs a circuit out past
the cookie's 8-hour idle lifetime or when a role it holds is no longer granted
by GroupToRole. LDAP membership changes and sign-out in another tab are still
only picked up at the age limit or on reconnect (documented).
2026-12-03 09:59:08 -05:00
Joseph Doherty 9c3a4c0eae fix(sessions): drop per-session event metrics after the session dispose (WRK-008, #253) 2026-12-03 09:57:41 -05:00
Joseph Doherty 196465ef9c fix(workers): fail fast when the worker exits before connecting; launch-cleanup Kill never masks the launch error (WRK-002, WRK-006, #253) 2026-12-03 09:56:05 -05:00
Joseph Doherty 835ed0bd04 fix(auth): revoking, rotating or deleting a key ends its open gRPC streams (SEC-004)
A streaming call was authenticated only at open, and revoke/rotate/delete only
evicted the verification cache, so a leaked key's open StreamEvents/StreamAlarms
kept delivering after the revoke. The interceptor now registers every streaming
call by key id in ApiKeyStreamRegistry and gives the handler a call context
whose token also fires on revoke; the dashboard key actions call Revoke, and the
call ends with Unauthenticated.
2026-12-03 09:55:43 -05:00
Joseph Doherty 2c22ae6bd4 fix(workers): bound the heartbeat skip by heartbeat age on the monotonic clock; deadline covers the enqueue; a reply that wins the timeout race is returned (WRK-001, WRK-003, WRK-004, WRK-005, #253) 2026-12-03 09:52:19 -05:00
Joseph Doherty 824107a56b fix(auth): cached verifications skip the limiter; success no longer wipes the key aggregate (SEC-002, SEC-003, #245)
SEC-002: once a key id's cross-peer aggregate tripped, every request for it -
including the holder's cached ones - competed for one probe slot per interval,
so a spray of bad secrets against the public key id denied the key to its
holder. The interceptor and /metrics handler now serve a cached success before
consulting the limiter, and an address that verified the key in the window is
exempt from the aggregate on a cache miss.

SEC-003: Reset removed the aggregate on every success, so a key in steady use
never accumulated one. Success now clears only the caller's own partition; the
aggregate decays by window.

Also corrects the MetricsAuthenticationHandler remark left stale by SEC-001.
2026-12-03 09:51:08 -05:00
Joseph Doherty a9f884f370 fix(auth): partition the API-key failure limiter on remote IP, not IP:port (SEC-001, #244)
ServerCallContext.Peer carries the client's ephemeral source port, so every new
connection was a fresh limiter partition and a sprayer could reconnect before
reaching the limit. Both auth surfaces (gRPC interceptor, /metrics handler) now
derive the partition address through ApiKeyThrottlePeer, which strips the port
and reduces IPv4-mapped IPv6 to IPv4.
2026-12-03 09:48:03 -05:00
Joseph Doherty 159524edd9 fix(dashboard): close the dropped live-read session; subscribe-and-track off the caller's token (DSH-002 #248, DSH-007, #253) 2026-12-03 09:47:46 -05:00
Joseph Doherty 27fdb576ba fix(dashboard): enforce page [Authorize] on in-circuit navigation via AuthorizeRouteView (DSH-001, #243)
Routes.razor used RouteView, which ignores [Authorize]. With the interactive
router, an in-circuit navigation never meets endpoint authorization, so anonymous
localhost could open /alarms and a Viewer could open /admin/secrets (secret
metadata list). Both were confirmed reachable by the new route test before the
change; AuthorizeRouteView now renders a Not Authorized panel instead.
2026-12-03 09:46:31 -05:00
Joseph Doherty 0673b0c76c fix(sessions): start the host session drain at ApplicationStopping, before Kestrel's drain (SES-001, #247) 2026-12-03 09:46:17 -05:00
Joseph Doherty 97e4d96afa fix(grpc): check AddBufferedItem read constraints; fail closed on unclassified command kinds (SES-003, #242)
AddBufferedItem carries an item_definition but fell into the default branch of
ApplyConstraintsAsync, so a read-constrained key could add and advise an
out-of-scope tag. It now runs EnforceReadTagAsync. The switch also fails
closed: kinds are explicitly classified as constraint-checked or tag-free, any
other kind is refused with PermissionDenied and an audited denial, and a test
enumerates MxCommandKind so a new kind must be classified.
2026-12-03 09:41:50 -05:00
Joseph Doherty cf00f6fc86 fix(grpc): owner-scope Invoke and CloseSession like StreamEvents (SES-002, #241)
A foreign API key holding the matching scope could Invoke(DrainEvents) another
key's session (dequeuing its events), write through it, or close it. Invoke and
CloseSession now apply the same ordinal owner compare as the StreamEvents
attach and return PermissionDenied. No admin override (D2): operators use the
dashboard, which calls ISessionManager directly.
2026-12-03 09:40:41 -05:00
Joseph Doherty 3d4d5f2b04 fix(sessions): renew the lease on last-subscriber detach; purge item registrations on Unregister (SES-004, SES-007, #253) 2026-12-03 09:39:21 -05:00
Joseph Doherty 027d2b5d1a perf(gateway): read worker frames through a 64 KiB read-ahead buffer (#235)
The gateway read each frame with two exact reads, one for the 4-byte prefix and
one for the body, so every frame cost two pipe I/O completions and two
thread-pool wake-ups. WorkerFrameReader now reads as much as its buffer has
room for, so one read normally serves a whole frame or a batch of frames.

Length checks still run on the prefix before any payload allocation; frames
larger than the buffer are assembled in a pooled array; EOF anywhere reports
EndOfStream with an EndOfStreamException inner exception as before. New tests
cover multiple frames per read, frames split across reads, frames straddling
the buffer end, frames larger than the buffer, oversize frames with their body
buffered, and EOF in the prefix, body, large body and at a frame boundary.
2026-12-03 09:36:30 -05:00
Joseph Doherty 9b9fdecc9b perf(gateway): attach the dashboard mirror only while a viewer watches (#235)
Every session ran a dashboard-mirror distributor subscriber that woke for every
event only for Publish to discard it, since normally nobody has a
session-details page open. The viewer registry now raises
ViewerPresenceChanged on a session's first viewer and last viewer; the
production broadcaster exposes it as IDashboardViewerPresence, and a session
attaches its mirror while watched and disposes the lease when not.

MarkReady still starts the pump, so draining, replay retention, the alarm lease
and dead-worker detection are unchanged. ACL and value redaction are untouched.
Broadcasters without presence (test doubles) keep the always-on mirror.

Internal distributor subscribers can now pass a filter applied before the
pump's TryWrite; the alarm monitor admits only alarm transitions and provider
mode changes, so data changes no longer wake it.
2026-12-03 09:36:30 -05:00
Joseph Doherty 5516561084 perf(gateway): run the worker event hand-off inline instead of two pool hops (#235)
The staging channel and the worker event channel now allow synchronous
continuations, so an event moves from the pipe read loop through the event
writer into the distributor pump on one thread. At ~240 ev/s each removed pool
work item ended in a PortableThreadPool spin-wait.

Subscriber channels keep asynchronous continuations, so no gRPC, dashboard or
alarm consumer code runs on the read loop. A full event channel still parks the
writer on an await and returns to the read loop; both overflow faults, ordering
and replay behavior are unchanged. The queue-depth gauge now increments before
the staging write, since the consumer can decrement inside it.

Documented under 'Event path threading' in docs/GatewayProcessDesign.md.
2026-12-03 09:36:30 -05:00
Joseph Doherty e811b93eb8 feat(worker,gateway): report record-info pin outcome in WorkerReady; drain-thread completion tests
The worker logged its MXSTATUS_PROXY record-info pin outcome only to its own
stderr, which the gateway's launcher does not capture, so operators never saw
whether the pin took.

- Contract (additive, internal IPC): WorkerReady.record_info_pin_status = 5.
  No protocol version bump; an older peer ignores it or sends it empty.
  Regenerated Contracts/Generated, the client protoset, the Rust vendored
  proto, and the Go/Python/Java worker bindings (real delta only).
- Worker: the handshake copies MxStatusProxyRecordInfoPin.Status into
  WorkerReady unless the runtime already set it.
- Gateway: WorkerClient records it (IWorkerClient.RecordInfoPinStatus, default
  null) and logs it at Information when pinned, Warning otherwise; empty is
  not logged. Shown as "Record-info pin" in the dashboard session details
  Worker table via DashboardSessionSummary.WorkerRecordInfoPinStatus.
- Tests: drain-thread cancellation (task ends Canceled; RunAsync cancels,
  runtime disposed, thread exits, no EventDrain stop-failure log) and fault
  (exception on the thread faults RunAsync with the same instance) paths;
  WorkerReady carries the pin status; gateway logging/recording and the
  dashboard projection.
- Docs: gateway.md STA thread model (drain thread, pin step in COM lifetime),
  MxAccessWorkerInstanceDesign, GatewayProcessDesign, GatewayDashboardDesign,
  WorkerFrameProtocol.
2026-12-03 09:36:30 -05:00
Joseph Doherty f6a3e13bd3 perf(worker,gateway): pin MXSTATUS_PROXY record info, dedicated event-drain thread, cap thread-pool spin
At ~240 events/s the worker burned 8-12% system CPU on wonder-app-vd03. A WPR
trace put 72% of it in lmxproxy's per-event GetRecordInfoFromGuids (type
library reload through the registry, amplified by WOW64 and the EDR registry
filter) and 26% in the .NET Framework thread pool spinning after each
per-event work item.

- Worker: MxStatusProxyRecordInfoPin holds the LMXProxy ITypeLib and the
  MXSTATUS_PROXY IRecordInfo for the process lifetime, so oleaut32 serves the
  per-event lookup from cache (~1 ms -> <1 us per call). Best-effort, never
  fatal; status logged at handshake.
- Worker: the event drain loop runs on a dedicated background thread with a
  synchronous wait and a synchronous pipe flush, removing the per-event
  thread-pool hops.
- Gateway: runtimeconfig sets ThreadPool.UnfairSemaphoreSpinLimit=10 to cut
  PortableThreadPool spin-wait CPU.

windev bench at ~242 ev/s: worker 67% -> 6.2% of one core; gateway 8.1% -> 6.9%.
Worker suite 785 passed / 14 skipped (x86, windev).
2026-12-03 09:36:30 -05:00
Joseph Doherty 26a90883fa Unify gateway styling and preserve identity through recovery
ci / java (push) Failing after 15m11s
ci / nightly-windev (push) Failing after 10m18s
ci / portable (push) Failing after 27m42s
ci / windows-x86 (push) Failing after 22m19s
2026-11-13 20:12:00 -05:00
Joseph Doherty b06921ce85 Lead gateway overview with readable fault context 2026-11-13 19:30:52 -05:00
Joseph Doherty c9a6c31cb8 feat(dashboard): make Galaxy browse and watch accessible 2026-11-13 18:19:08 -05:00
Joseph Doherty 260d58afa1 fix(dashboard): pilot native dialog focus and safe dismissal 2026-11-13 17:51:02 -05:00
Joseph Doherty 453fe01525 chore(deps): ZB.MOM.WW.Telemetry(.Serilog) 0.3.0 -> 0.3.1 (scadaproj#56)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 2m25s
ci / java (push) Failing after 22m3s
ci / portable (push) Failing after 22m28s
0.3.1 stops the gRPC/HttpClient instrumentation tracing telemetry's own
OTLP export calls (the Serilog log sink's LogsService/Export spans).
The app's own outgoing gRPC/HTTP spans are unchanged.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-12 22:16:31 -05:00
Joseph Doherty d9d9ff489b feat(telemetry): Telemetry 0.3.0 - service.version, site.id/node.role, logs over OTLP (scadaproj#55)
ci / java (push) Failing after 11m45s
ci / windows-x86 (push) Successful in 3m47s
ci / portable (push) Failing after 26m59s
ci / nightly-windev (push) Failing after 14m4s
Pins ZB.MOM.WW.Telemetry(.Serilog) 0.1.0 -> 0.3.0. AddZbTelemetry now reads the whole
MxGateway:Telemetry section through the shared ApplyConfiguration: node.role defaults
to "standalone" (one gateway per box), MxGateway:Telemetry:SiteId / :NodeRole /
:ServiceVersion / :ResourceAttributes:* are operator keys, and service.version
defaults to the entry assembly's informational version (the git SHA). With
MxGateway:Telemetry:Exporter=Otlp the Serilog logs go to the same collector too.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-12 21:24:39 -05:00
Joseph Doherty afd504d5ae feat(events): opt-in stream-attached acknowledgement on StreamEvents (#227)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m28s
ci / java (push) Failing after 2m21s
ci / portable (push) Failing after 3m33s
A fresh StreamEvents is never replayed, so an initial value published before
the gateway registers the stream's subscriber is lost (lmxopcua#865 —
slow-changing ScanState). Clients had nothing deterministic to wait on.

Contract (additive, proto3):
- StreamEventsRequest.emit_stream_attached = 3 (bool, default false)
- MxEvent.stream_attached = 15 (optional StreamAttached)
- message StreamAttached { uint64 live_after_sequence = 1; }
- OpenSessionReply capability "stream-events-attached-ack"
  (GatewayCapabilities.StreamEventsAttachedAck)

When requested, EventStreamService yields the sentinel as the FIRST message,
after AttachEventSubscriber/AttachEventSubscriberWithReplay has returned, so
receipt implies registration; refused attaches never see it. It precedes the
ReplayGap sentinel and replay on a resume. Shape mirrors ReplayGap: family
UNSPECIFIED, no body, worker_sequence 0.

Opt-in rather than always-on: ScadaBridge's MxGateway adapter stores every
streamed event's worker_sequence as its resume cursor, so an unrequested
sentinel would reset it to 0. Default wire behaviour is unchanged.

.NET client: StreamEventsAsync/StreamEventItemsAsync(after, emitStreamAttached),
MxEventStreamItem.IsStreamAttached, MxGatewaySession.SupportsStreamAttachedAck,
and OpenEventStreamAsync -> MxGatewayEventStream (awaits the sentinel, with
attach timeout; refuses older gateways).

Regenerated Contracts/Generated, the client protoset, Go and Python bindings
(also picks up comment-only drift already on main), synced the Rust vendored
proto and set emit_stream_attached in the Rust StreamEventsRequest literals.
No package versions bumped.

Tests: ordering (sentinel first, then events), race proof (event fanned right
after the sentinel is delivered — mutation-checked: fails when the sentinel is
yielded before registration), resume-with-gap order, refused attach emits no
sentinel, default emits none, contract field numbers, capability, and .NET
client wire tests (await, no-capability, older gateway, timeout).
2026-11-12 07:27:17 -05:00
Joseph Doherty 2b13564e04 feat(ldap): pin the LDAP server certificate by SHA-256 thumbprint (#180)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m26s
ci / java (push) Successful in 2m15s
ci / portable (push) Failing after 4m19s
New optional MxGateway:Ldap:ServerCertificateThumbprintSha256 (hex SHA-256
of the DER cert; case/colon/dash/space-insensitive; comma/semicolon-separated
string or array, so a rotation can carry old + new). When set, the dashboard's
shared LDAP provider gets a RemoteCertificateValidationCallback via
LdapOptions.ServerCertificateValidationCallback (Auth 0.4.1) that accepts the
server certificate iff its thumbprint matches a pin, ignoring chain/name
errors only then. Unset keeps default OS trust-store validation untouched.

The callback is an init-only, code-only property, so the ILdapAuthService
registration from AddZbLdapAuth is replaced with one built from the bound
options plus the callback. Pins are read straight from configuration because
the binder silently binds the scalar form onto a list as empty.

GatewayOptionsValidator rejects a pin that is not 64 hex chars after
normalization and any pin with Transport=None; the Production hard stops are
unchanged. Pins are shown on the Settings page. Docs: GatewayConfiguration.md,
glauth.md.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-10 11:52:14 -05:00
Joseph Doherty ace12f81ad build(deps): bump ZB.MOM.WW.Auth 0.3.0 -> 0.4.1 (scadaproj#5)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m27s
ci / java (push) Successful in 2m44s
ci / portable (push) Failing after 4m59s
Auth 0.4.1 (BindMode stays ServiceAccount; empty password now refused in the library too; Username canonicalised from UserNameAttribute). No API breaks, no test changes needed.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 18:16:27 -05:00
Joseph Doherty e1656f214b build(deps): bump ZB.MOM.WW.Theme 0.4.1 -> 0.5.0 (scadaproj#9)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m27s
ci / java (push) Successful in 2m30s
ci / portable (push) Failing after 5m10s
Mobile shell fix: closed navigation no longer hides page content.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 15:48:16 -05:00
Joseph Doherty 7a7ef3b89f fix(config): align GatewayConfigPathRules with Secrets-005 (symlinks, drive-relative, device/loopback/local-share spellings) (scadaproj#52)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m30s
ci / java (push) Successful in 2m17s
ci / portable (push) Failing after 4m20s
Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 15:40:32 -05:00
Joseph Doherty 259d375022 feat(audit): stamp CorrelationId on dashboard API-key admin audit events (mxaccessgw#213)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m29s
ci / java (push) Successful in 2m13s
ci / portable (push) Failing after 4m12s
CanonicalForwardingApiKeyAuditStore now derives CorrelationId from the ambient
request: Activity.Current trace id, else the HTTP request TraceIdentifier
(GUID used verbatim, otherwise hashed to a stable GUID) via an optional
IHttpContextAccessor. The CLI path has neither and stays null. Auth library
unchanged (option b).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 15:04:03 -05:00
Joseph Doherty fccc21ba8e feat(events): distinguish ResourceExhausted causes with an mxgw-reason trailer (mxaccessgw#216)
Event-queue overflow, alarm-feed overflow, subscriber cap, session limit and
oversized commands all surfaced as ResourceExhausted. The status code is
unchanged; the gateway now attaches a machine-readable `mxgw-reason` trailer
(constants in Contracts ResourceExhaustedReasons). The .NET client maps
ResourceExhausted to MxGatewayResourceExhaustedException (an
MxGatewayException subclass; additive) exposing Reason/IsOverflow/
IsSubscriberLimit. Documented in docs/ClientBehaviorFixtures.md; the other
clients get a doc note only.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 15:02:24 -05:00
Joseph Doherty 716c845fc7 build(server): bump Microsoft.Data.Sqlite to 10.0.13 with SQLitePCLRaw.lib.e_sqlite3 2.1.13 (mxaccessgw#225)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m28s
ci / java (push) Successful in 2m8s
ci / portable (push) Failing after 4m9s
Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 14:21:21 -05:00
Joseph Doherty 09b3ecddf2 test: pump-idle signal for DashboardSnapshotFeed; fold private wait helpers into Eventually (mxaccessgw#223)
The MxGateway.Tests part of #223 (the Worker.Tests items are handled separately).

- DashboardSnapshotFeed gains two internal test seams: WhenIdleGateClosedAsync, a
  TCS-backed signal that completes once no pump generation is accepting subscribers,
  and IsPumpIdle (no live generation and the latest pump has exited). The TCS is created
  lazily by a waiter, so production never allocates it.
- WatchAsync_WhenAJoinerLeavesWhileAnOldGenerationLingers_LeavesNoPumpRunning drops both
  150 ms real sleeps: it waits on the idle-gate signal for the joiner's unsubscribe, and
  asserts IsPumpIdle before the orphan-push check, which is then immediate. Reverting the
  per-generation idle check to the old global "list is empty" check now fails the test
  (5 s TimeoutException on the gate), where before the sleep simply elapsed.
- Eventually.WaitUntilAsync/WaitForAsync take an optional description (defaulting to the
  condition's source text via CallerArgumentExpression) for the timeout message, and gain an
  async-condition overload. The hand-rolled polling loops in EventStreamServiceTests,
  GatewaySessionDashboardMirrorTests, DashboardEventBroadcasterTests and
  AlarmsPageTruncationBannerTests now delegate to it, keeping their timeouts and messages.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 13:36:34 -05:00
Joseph Doherty 22964e192b feat(gateway,worker): configurable worker watchdog grace; heartbeat settings in effective config and Settings page (mxaccessgw#224)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m24s
ci / java (push) Successful in 2m15s
ci / portable (push) Failing after 4m17s
- New MxGateway:Worker:WorkerHeartbeatGraceSeconds (default 15), exported as
  MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS and read by WorkerPipeSessionOptions.FromEnvironment
  (a grace the ceiling does not exceed falls back to the default so the worker
  still starts). Validation now checks WorkerHeartbeatStuckCeilingSeconds against
  the configured grace; the copied WorkerWatchdogGraceSeconds constant is gone.
- EffectiveWorkerConfiguration and the dashboard Settings page now show the worker
  heartbeat send interval, watchdog grace and stuck ceiling (render test added).
- Docs updated.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 13:29:10 -05:00
Joseph Doherty 2e52f9f5e8 feat(gateway,worker): configurable worker heartbeat send interval and stuck ceiling (mxaccessgw#218)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m32s
ci / java (push) Successful in 2m57s
ci / portable (push) Failing after 5m1s
The worker's heartbeat send interval (5 s) and its own STA-watchdog stuck
ceiling (75 s) were compile-time defaults the gateway never reached, and
nothing checked that the gateway's HeartbeatGraceSeconds exceeded the real send
interval, so a misconfigured grace could kill healthy workers.

- New MxGateway:Worker options WorkerHeartbeatSendIntervalSeconds (default 5)
  and WorkerHeartbeatStuckCeilingSeconds (default 75), exported by
  WorkerProcessLauncher as MXGATEWAY_WORKER_HEARTBEAT_SEND_INTERVAL_MS and
  MXGATEWAY_WORKER_HEARTBEAT_STUCK_CEILING_MS, the same env-var path the other
  worker settings use.
- The worker's production WorkerPipeSession reads them through
  WorkerPipeSessionOptions.FromEnvironment; a missing/invalid value, or a
  ceiling not above the worker's 15 s watchdog grace, keeps the default rather
  than failing the worker.
- Startup validation: HeartbeatGraceSeconds > WorkerHeartbeatSendIntervalSeconds;
  send interval > 0; worker ceiling > 15 s; both at most 86400 s.
- Docs: GatewayConfiguration, WorkerProcessLauncher (env table now also lists
  the previously missing MXGATEWAY_ALARM_ACK_CLIENT_NAME), worker design doc.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 13:24:05 -05:00
Joseph Doherty bc28e1436b fix(dashboard): apply reconnect delay when the snapshot watch completes cleanly (mxaccessgw#222)
Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 13:12:40 -05:00
Joseph Doherty 82d29beafd test: fake time for dashboard snapshot publisher; signal-based waits (mxaccessgw#205)
DashboardSnapshotPublisher takes an optional TimeProvider (default
TimeProvider.System) driving the idle poll, the reconnect delay and, via
BoundedHubSend, the send timeout. Its tests now run on a fake clock with
exact assertions (reconnect gap == delay, 25 idle polls pull nothing, a
wedged send is abandoned at the fake send timeout).

DashboardSnapshotFeed has no time dependence, so no seam was added; its
tests lose the 100 ms sleep and poll loops in favour of CountSignal
signals. The Task.Delay(25) poll copies in the alarm-monitor tests and
several 5-10 ms poll loops now share TestSupport/Eventually.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 13:10:04 -05:00
Joseph Doherty 8c21678cb4 feat(health): worker-exe presence and bounded Galaxy SQL readiness checks (mxaccessgw#206)
Adds WorkerExecutableHealthCheck (configured worker .exe exists) and
GalaxySqlHealthCheck (IGalaxyRepository.TestConnectionAsync bounded by a 5 s
TimeProvider-driven timeout). Both are tagged ready only, never live, so an
outage takes the node out of rotation without triggering a restart; sessions
stay on the active tier so zero sessions is still healthy for Overview.

Registrations move into AddGatewayHealthChecks() so the tier tagging is
unit-tested. LDAP is not added (sign-in already surfaces bind failures).
docs/Diagnostics.md lists the two new checks.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 12:58:07 -05:00
Joseph Doherty b5d11e5869 fix(worker): heartbeat check loop honours the injected TimeProvider (mxaccessgw#217)
HeartbeatLoopAsync waited with a plain Task.Delay, so heartbeat grace/stuck
detection could not be driven with a fake clock. It now uses
Task.Delay(interval, _timeProvider, ct).

Adds fake-time tests (grace boundary then fault; in-flight command within the
stuck ceiling) built on a new TickObservingTimeProvider, and replaces the
150 ms real-clock sleep in the within-ceiling negative test (mxaccessgw#205).
Both new tests fail without the fix.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 12:58:07 -05:00
Joseph Doherty f77062f097 feat(dashboard): show heartbeat, event-channel and replay-byte-cap options on Settings (mxaccessgw#219)
Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 12:42:12 -05:00
Joseph Doherty 07badd139e fix(gateway): bound the session replay ring by bytes as well as count (mxaccessgw#172)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m26s
ci / java (push) Successful in 2m28s
ci / portable (push) Failing after 4m48s
The replay ring was bounded only by ReplayBufferCapacity (1024 events) and
ReplayRetentionSeconds. Event size is unbounded up to the worker frame size,
so a burst of large-array events could pin gigabytes per session while the
count looked small.

New MxGateway:Events:ReplayBufferMaxBytes (default 64 MiB, 0 disables) caps
the summed serialized size (MxEvent.CalculateSize, measured only when the cap
is on). Over the cap the oldest entries are evicted, exactly like the count
cap, so a resuming subscriber sees the existing ReplayGap path; an event bigger
than the whole cap is not retained. Every eviction (count, age or byte) now
clears its slot, so an evicted event is released immediately instead of
staying referenced until the slot is reused.

The 64 MiB default is a judgement call: it never binds for scalar traffic
(1024 x a few hundred bytes) and only trims large-array bursts.

Tests: SessionEventDistributorTests byte-cap eviction, single oversized event,
cap 0 = count only (the first two fail with the cap enforcement removed);
validator rejects a negative value. Docs: GatewayConfiguration.md, Sessions.md,
DesignDecisions.md; appsettings.json carries the key.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 12:39:49 -05:00
Joseph Doherty 7b21f304e9 fix(gateway): split the heartbeat check interval from the send interval; expose the two fixed worker-client timeouts (mxaccessgw#192)
R21-O14: MxGateway:Worker:HeartbeatIntervalSeconds was documented as the
worker heartbeat send interval, but it never reached the worker (which sends
on its own fixed 5 s) and only set the gateway's HeartbeatCheckInterval. It is
renamed HeartbeatCheckIntervalSeconds (default 5, unchanged). The old key stays
as a deprecated alias with the same meaning so existing appsettings keep
working; setting both is a validation error. The grace-vs-interval check now
compares against the resolved check interval.

R21-O15: WorkerClientOptions.EventChannelFullModeTimeout and
HeartbeatStuckCeiling were always their compile-time defaults. They are now
MxGateway:Worker:EventChannelFullModeTimeoutMilliseconds (default 5000, > 0)
and HeartbeatStuckCeilingSeconds (default 75, >= HeartbeatGraceSeconds). The
factory's mapping moved into SessionWorkerClientFactory.CreateWorkerClientOptions
so every field is set from configuration and is testable. The effective-config
record shows the resolved check interval and both new values.

Docs: GatewayConfiguration.md, GatewayProcessDesign.md sample,
MxAccessWorkerInstanceDesign.md heartbeat section; appsettings.json uses the
new keys.

Tests: CreateWorkerClientOptions mapping + defaults (fail under a mutated
mapping), alias honoured, both-keys conflict, and bounds for the new options.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 12:39:49 -05:00
Joseph Doherty 101bda7073 fix(gateway): wake the worker-ready wait on a state-change signal instead of a 25 ms poll (mxaccessgw#189)
GetReadyWorkerClientAsync re-read the session and worker states every 25 ms
until the WorkerReadyWaitTimeoutMs deadline. It now waits on two
TaskCompletionSource signals - one completed by every GatewaySession _state /
_workerClient write, one by every WorkerClient _state write - and re-evaluates
only when one fires or the remaining budget elapses. Both signals are captured
under the lock before the state is evaluated, so a transition between the
evaluation and the await is not lost.

IWorkerClient gains GetStateChangedSignal(), a default interface member that
returns null; a client without a signal (the test fakes) is re-read on the old
25 ms interval, so the fakes need no change. The production WorkerClient always
publishes one. Default behaviour (WorkerReadyWaitTimeoutMs = 0, fail fast) is
unchanged.

Regression tests (SessionManagerTests): ...WakesWithoutPollTimer and
...FailsFastWithoutPollTimer never advance the FakeTimeProvider, so they hang
and fail against the poll loop; WorkerClientTests.GetStateChangedSignal_
CompletesOnEachTransition pins the worker-side signal.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 12:39:49 -05:00
Joseph Doherty 11d8f76c5f fix(gateway): GatewaySession implements IAsyncDisposable; drop dead KillWorker(string) (mxaccessgw#191)
R21-O12: GatewaySession already owned an async DisposeAsync teardown but did not
declare IAsyncDisposable, so anything holding it as IAsyncDisposable (or a DI
container) could not find the teardown. Declaring it changes no call site;
the existing await-using sites bound to the same method by pattern.

R21-O13: KillWorker(string) had no callers and was an ungated kill that
bypassed _closeLock. Deleted it; docs/Sessions.md and the test comments now
name KillWorkerWithCloseGateAsync, the real kill path.

Regression test: GatewaySessionTests.GatewaySession_ImplementsIAsyncDisposable
(fails before the interface is declared).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 12:39:49 -05:00
Joseph Doherty d56353bf08 fix(gateway): remove the orphaned mxgateway.retries.attempted instrument (mxaccessgw#215)
The launcher's Polly startup-probe pipeline was its only recorder and was
removed in mxaccessgw#188, so the counter, the RetryAttempted method and the
snapshot's RetryAttempts / RetryAttemptsByArea fields carried a permanent
zero. No dashboard page or in-repo alert rule references them. Metrics.md
drops the row and the snapshot shape (which also gains the missing
AlarmProviderSwitchCount field).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 12:39:49 -05:00
Joseph Doherty e69cd0321e fix(dashboard): close three low hub/page races (mxaccessgw#174)
D11: BrowsePage search CTS is cancelled+disposed exactly once under a lock.
D12: the hub refreshes the cached health status before seeding a new connection.
D13: DashboardEventBroadcaster gains DisposeAsync that awaits the pumps (bounded).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 12:30:04 -05:00