The poll loop skipped the STA hop while unsubscribed but its timer still woke
every interval (a Task.Delay timer plus a thread-pool continuation per tick on
every idle worker). It now parks on a semaphore while IsSubscribed is false and
is released by the handler's new SubscriptionActivated event; a subscribe that
races the park is kept by the semaphore count. While subscribed it never parks,
so failover polling and probes (MXA-001) are unchanged, and shutdown cancels a
parked loop like a sleeping one, so the MXA-003 join and grace bound hold. The
failure run resets when the loop parks.
UpdateAlarmWatchList rebuilt the standby: a second MXAccess registration, an
AddItem/Advise for every watched subtag, then an Unregister of the old source —
work proportional to the whole list for a one-alarm change (reproduced by the
previous commit's test). The subtag standby now takes the list as a diff:
added alarms' subtags are advised on the existing source, removed alarms'
subtags are unadvised, and unchanged alarms keep their advice and state.
The update stays all-or-nothing: the list is validated and the additions
advised before the swap, and an advise failure unadvises what it added and
keeps the previous list. A changed target starts fresh and is initialised from
the last delivered subtag values (acked/priority before active, MXA-007; bad
quality still ignored, MXA-005). LmxSubtagAlarmSource tracks an item from
AddItem so an Advise failure is retryable and removable.
IWorkerClient gains MaxCommandBytes (the negotiated frame maximum less the
sequence-stamp allowance, the bound its CommandTooLarge pre-check uses).
GatewaySession passes it as a byte budget into SparseArrayExpander, which
charges a lower bound of each expanded array's encoding (default-valued slots)
before allocating, so an oversized sparse write - or a bulk command whose
sparse values together overrun the frame - is rejected with InvalidArgument
without the million-slot allocation.
JS now reports when a submit raises its in-flight pending flag, and a cancel
request marks the same, so the next render clears pending through update()
without update() running on every snapshot tick. Escape still works after a
rejected submit.
Conflicts resolved:
- WorkerClient: keep the WRK-003 deadline-bound enqueue and carry the WRK-010 pre-computed
envelope size through both the TryWrite fast path and the slow path.
- AlarmsHub: prime each connection (DSH-005) and then count it for the idle-gated publisher
(DSH-009); a connection that fails priming is never counted, so never decremented.
- GatewayDashboardDesign.md: describe both.
- SEC-005: a lifecycle that ends keeps its cache as the previous
generation; the next lifecycle's first reconcile diffs against it and
broadcasts Clear for alarms gone during the gap (derived from the new
worker snapshot, documented in gateway.md as a reconcile repair, not a
synthesized event). The retired set is hidden from CurrentAlarms; gap
joiners get the whole set. Each lifecycle start broadcasts its
re-baselined provider status.
- SEC-006: live transitions stamp a sequence; a reconcile leaves alarms
changed live after it was issued alone (no stale Clear / re-raise).
- SEC-007: an Acknowledge of an uncached alarm is broadcast but no longer
inserts an ActiveAcked row; other non-Raise kinds do not touch the cache.
- SEC-009: a changed original raise time is a Raise repair; a non-OK
reconcile is logged/surfaced and fails the initial reconcile.
- SEC-008: watch-list resolution cached per Galaxy deploy time and
fingerprinted by SHA-256 once per resolution; refresh runs on its own
loop; the failover-edge refresh is bounded to 10 s.
- SEC-010: restart backoff doubles from 5 s to a 5 min cap and resets on
Monitoring; repeated identical faults log one summary line.
The publisher's single monitor subscription is primed once, normally
before any browser connects, so a later client saw only subsequent
transitions and never the standing alarms or provider status.
AlarmsHub.OnConnectedAsync now joins the group, sends the caller a
generation-0 AlarmFeedReset, then the status frames, active alarms and
snapshot_complete from a fresh subscription, redacted by ShowTagValues.
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).
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.
ReconcileIntervalSeconds must be 1..86400 when alarms are enabled (a huge
value faulted PeriodicTimer inside an unobserved task, silently ending
reconciliation); ReplayRetentionSeconds must be finite and at most a day
(Infinity passed startup and then threw in TimeSpan.FromSeconds on every
StreamEvents). A faulted reconcile loop is now logged and surfaced.
LmxSubtagAlarmSource now passes the OnDataChange quality through. The
subtag state machine ignores InAlarm/Acked updates that are not good
quality or carry no value instead of coercing them to false (which read
as a Clear). An Acked=true buffered before the first InAlarm value is
the initial state of an already-acked alarm and survives the raise.
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.
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.
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.
An OnDataChange/OnWriteComplete already queued on the STA is dispatched
after RemoveItem evicted the handle and re-created the cache entry; item
handles are never reused within a registration, so it leaked until
Unregister. MxAccessSession.Create now binds its handle registry to the
production sink, which only caches callbacks for handles the registry still
holds. The event is still forwarded. EvictStaleHandleState stays as the
backstop for unbound sinks.
Per D9: a request the worker rejects before calling MXAccess (write value
with no kind, raw payload, empty MxArray) throws the new
WorkerRequestValidationException and replies INVALID_REQUEST with no
HRESULT. A plain ArgumentException stays MXACCESS_FAILURE with its HRESULT,
because the interop raises MXAccess E_INVALIDARG that way. The dispatcher
now converts executor exceptions on the STA, so anything the InvokeAsync
await throws is the runtime refusing the work item (shutdown, disposal,
dead loop, canceled at shutdown) and replies WORKER_UNAVAILABLE. No .proto
change. Status mapping documented in docs/WorkerConversion.md.
Typed array projection no longer throws on an element that does not fit:
it falls back to the array's own element type, then to the raw projection
with a diagnostic naming the element index and CLR type. Time arrays parse
BSTR timestamps as MXAccess local time and reject 32-bit/double elements
instead of reading them as FILETIMEs near 1601; out-of-range FILETIMEs
(scalar and array) stay integers. Integer arrays widen like the scalar
path: uint/long/ulong use Int64Values, object[] retries as Int64 on
overflow, and a ulong above long.MaxValue takes the raw projection.
Conversion runs on the event path, where a throw faults the session.
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.
An unbounded PeekMessage drain never returned while inbound COM callbacks
arrived at least as fast as they dispatched, so the STA loop stopped running
queued commands and stopped stamping LastActivityUtc; the heartbeat watchdog
then faulted a busy apartment as StaHung. The record-info pin raises the
dispatch ceiling a lot but is best-effort, and the drain was still unbounded.
Each pump pass now dispatches at most StaMessagePump.MaxMessagesPerPass (64),
then the loop stamps activity and services the command queue. MWMO_INPUTAVAILABLE
makes the next wait return at once while input remains, so no wakeup is lost.
StaRuntime.PumpPendingMessages (the pump step of ReadBulk/write waits) uses the
same cap so those loops re-check their deadline between slices.
Tests: a fake message flood with a queued command (command runs, activity stays
fresh, no pass exceeds the cap); a real-queue test that a pass stops at the cap.
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.
ReadBulk served a tag from the cache only when it was advised and cached;
every other tag took the AddItem + Advise + wait + UnAdvise + RemoveItem
snapshot lifecycle. If AddItem ever returned the caller's existing handle,
the teardown would unadvise and remove the caller's subscription.
ReadBulk now resolves a tag the session already holds to the session's
own item handle in phase 1:
- advised but uncached: wait on the caller's subscription for its first
OnDataChange (baseline taken in phase 1, before any phase-2 pump can
dispatch it); no COM call, no teardown.
- added but not advised: advise temporarily, then unadvise only; the item
stays registered, and the value the temporary advice cached is dropped
so it cannot later be served as was_cached = true.
- not held: unchanged snapshot lifecycle. An AddItem that returns a handle
the registry already tracks is treated as the caller's (not
re-registered, not removed).
Duplicate sharing, pump cadence, the shared deadline, timeout reporting
and was_cached semantics are unchanged.
Live repro on the windev rig (330 advised + 40 added-only tags, immediate
250-tag ReadBulk chunks x4 parallel, 60 s observation): unfixed and fixed
workers both keep 290/330 handles delivering. The 40 silent handles are
TestHistoryValue, which does not change within the window on either
build. The installed MXAccess hands out a distinct handle per AddItem
even for an address already added, and UnAdvise/RemoveItem of the second
handle leaves the first delivering. So the #238 teardown path does not
silence subscriptions on this MXAccess, and this change does not explain
the vd03 rate drop. The fix stays as a guard, and it saves an extra item
and four COM calls per uncached held tag.
Docs: gateway.md, Contracts.md, DesignDecisions.md,
MxAccessWorkerInstanceDesign.md and the five client ReadBulk doc comments.
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.
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.
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.
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.
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).