34 KiB
34 KiB
Clients (.NET / Go) — Bugs and Performance Review
- Date: 2026-12-02
- HEAD:
54367e74 - Scope:
clients/dotnet/(ZB.MOM.WW.MxGateway.Clientlibrary +ZB.MOM.WW.MxGateway.Client.Cli) andclients/go/(mxgatewaypackage +cmd/mxgw-go). Generated code and tests excluded. The server (src/ZB.MOM.WW.MxGateway.Server/Grpc/,Workers/WorkerClient.cs) was read only to confirm what the wire actually carries. - Method: read-only source review. No repo file was modified and no repo project was built. One language-level claim (CDN-003) was reproduced with a throwaway console program outside the repo. "Confirmed" means the defect is visible in the cited code; "Plausible" means the code path is confirmed but the runtime impact depends on network or server behaviour that was not reproduced.
Neither client implements automatic reconnect. Both expose after_worker_sequence resume and surface ReplayGap as a typed signal, and that plumbing is correct: Go clears Event on a gap result (session.go:1130-1132), .NET exposes it through MxEventStreamItem and consumes the StreamAttached sentinel in OpenEventStreamAsync. No duplicate-event or lost-event defect was found in the resume path itself. The findings are about what happens around it: how stream and call termination is classified, liveness on a dead connection, disposal, and credential attachment.
Summary
| ID | Severity | Category | Confidence | Title |
|---|---|---|---|---|
| CDN-001 | Medium | Bug | Confirmed | Server-sent Cancelled is mapped to OperationCanceledException even when the caller never cancelled |
| CDN-002 | Medium | Bug | Confirmed | Session loss arrives as gRPC NotFound / FailedPrecondition and is never mapped to MxGatewaySessionException |
| CDN-003 | Medium | Bug | Confirmed (mechanism reproduced; timing against real gRPC not) | MxGatewayEventStream.DisposeAsync throws NotSupportedException when a read is in flight |
| CDN-004 | Medium | Bug | Plausible | No HTTP/2 keepalive on the SocketsHttpHandler; deadline-less streams hang forever on a half-open connection |
| CDN-005 | Low | Bug | Confirmed | MxGatewaySession.DisposeAsync can block for about a minute and can throw OperationCanceledException |
| CDN-006 | Low | Performance | Confirmed | Owned SocketsHttpHandler (and pinned CA certificate) is never disposed with the channel |
| CDN-007 | Low | Performance | Confirmed | ResourceExhausted is retried as transient although every source of it is deterministic |
| CDN-008 | Low | Bug | Confirmed | RegisterAsync / AddItemAsync / AddItem2Async dereference a null ReturnValue on a payload-less reply |
| CDN-009 | Low | Bug | Confirmed | CLI: 30 s global cancellation applies to stream-events / stream-alarms / bench-read-bulk, and the resulting OperationCanceledException escapes unhandled |
| CDN-010 | Low | Bug | Confirmed | CLI: --value text is redacted from every error message, garbling diagnostics for short values |
| CDN-011 | Low | Performance | Confirmed | CLI batch mode builds a new channel (and a second one for Galaxy) per line |
| CGO-001 | Medium | Bug | Plausible | No keepalive dial option; deadline-less streams hang forever on a half-open connection |
| CGO-002 | Low | Bug | Confirmed | API key is attached only by dial-time interceptors: NewClient ignores Options.APIKey, and a caller WithUnaryInterceptor replaces auth |
| CGO-003 | Low | Bug | Confirmed | A stream ended by a context deadline or a server-sent Canceled closes the channel with no error |
| CGO-004 | Low | Performance | Confirmed | Stream context is never cancelled on EOF / terminal error; Events/EventsAfter leak one cancelCtx per stream |
| CGO-005 | Low | Bug | Confirmed | dialConnected waits the full timeout on an immediate failure and discards the real cause |
| CGO-006 | Low | Bug | Confirmed | WatchDeployEvents closes errs before events; the CLI can return with buffered events unprinted |
| CGO-007 | Low | Bug | Confirmed | Register / AddItem / AddItem2 return handle 0 on a reply without the payload |
| CGO-008 | Low | Performance | Confirmed | CLI batch mode does a blocking dial per line; bench-read-bulk spins on failures with no backoff |
.NET
CDN-001 — Server-sent Cancelled is mapped to OperationCanceledException even when the caller never cancelled
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcMxGatewayClientTransport.cs:238-248,GrpcGalaxyRepositoryClientTransport.cs:120-130(same code). Server origins:src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs:1077-1081(any server-sideOperationCanceledException),:1142(WorkerClientErrorCode.GatewayShutdown => StatusCode.Cancelled),src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs:491-494and:1142-1146(pending commands completed withGatewayShutdownwhen the worker client is closed or disposed). - Description:
MapRpcExceptionreturns anOperationCanceledExceptionwhencancellationToken.IsCancellationRequested || exception.StatusCode == StatusCode.Cancelled. The second arm fires for a status the gateway itself produced. The server completes every pending command withGatewayShutdownwhen a session's worker client is closed (session closed by another caller, dashboard Close/Kill, lease reaper, gateway shutdown), and that maps to gRPCCancelled. The exception is also constructed with the caller's token, which is not cancelled.DotnetClientDesign.md:157-158states the intended rule: surfaceOperationCanceledException"only when the caller initiated cancellation". - Failure scenario: A client has
WriteAsyncin flight when an administrator kills the session from the dashboard, or the gateway service is stopped for a deploy. The call throwsOperationCanceledException. Application code that follows the usual convention (catch (OperationCanceledException) { return; }meaning "we are shutting down") swallows it: the write outcome is unknown, no error is logged, and no reconnect is attempted. The same exception also bypassesMxGatewaySession.DisposeAsync's catch filter (CDN-005) and the CLI's top-level handler (CDN-009). - Suggested fix: Map to
OperationCanceledExceptiononly when the caller's token is cancelled. Map aCancelledstatus with a live token toMxGatewayException(or a typed "gateway shutting down / session closed" subtype) keeping theRpcExceptionas inner. - Test idea: Fake transport call that throws
RpcException(Status(Cancelled))with a non-cancelled token; assertInvokeAsyncthrowsMxGatewayException, notOperationCanceledException. Keep the existing caller-cancel test asserting OCE.
CDN-002 — Session loss is never mapped to MxGatewaySessionException
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcMxGatewayClientTransport.cs:250-263(status switch handles onlyUnauthenticated,PermissionDenied,ResourceExhausted),MxCommandReplyExtensions.cs:59-66(the only placeMxGatewaySessionExceptionis created). Server:src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs:1106-1107(SessionNotFound => StatusCode.NotFound,SessionNotReady => StatusCode.FailedPrecondition). - Description:
MxGatewaySessionExceptionis built only from a reply whoseProtocolStatus.CodeisSessionNotFoundorSessionNotReady. The gateway never returns those codes in a reply: theMxAccessGrpcMapper.SessionNotFound/SessionNotReadyhelpers have no callers in the server, andInvoke,StreamEventsandCloseSessionall throwRpcException(NotFound)/RpcException(FailedPrecondition)instead.MapRpcExceptionsends both to the baseMxGatewayException. The typed exception is therefore unreachable for the case it exists for. - Failure scenario: The gateway restarts (orphan workers are terminated, sessions are gone). A client resumes with
StreamEventsAsync(afterWorkerSequence)or issues a command and getsNotFound. Its recovery codecatch (MxGatewaySessionException) { reopen and re-subscribe }never runs; the error lands in the genericcatch (MxGatewayException)branch, which typically retries the same dead session id until it gives up. The only way to tell "session gone, reopen" from "transient, resume" is to dig((RpcException)ex.InnerException).StatusCodeout by hand. - Suggested fix: In
MapRpcException, mapNotFoundandFailedPreconditiontoMxGatewaySessionException(carrying the status detail and innerRpcException). Consider exposing the gRPCStatusCodeonMxGatewayExceptionso callers do not need the inner exception. - Test idea: Fake transport throwing
RpcException(Status(NotFound, "Session x was not found."))fromInvokeAsyncand from the event stream; assertMxGatewaySessionException.
CDN-003 — MxGatewayEventStream.DisposeAsync throws when a read is in flight
- Severity: Medium. Category: Bug. Confidence: Confirmed for the mechanism (reproduced in isolation: 199 of 200 iterations threw); the exact timing against a live gRPC call was not reproduced.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayEventStream.cs:67-83(dispose),:59(the in-flightMoveNextAsync),:95(_enumeratoris the compiler-generated iterator fromGrpcMxGatewayClientTransport.StreamEventsAsync,GrpcMxGatewayClientTransport.cs:82-113). - Description:
DisposeAsynccancels_lifetimeand immediately calls_enumerator.DisposeAsync(). A compiler-generated async iterator throwsNotSupportedExceptionfromDisposeAsyncwhile aMoveNextAsyncis still pending.CancelAsynconly guarantees the cancellation callbacks have run; the iterator's continuation that observes the cancelled read is scheduled separately, so the iterator is normally still suspended at itsawait.OpenAsyncin the same file already knows this rule and awaits the pending read before disposing (:137-150, "An async iterator cannot be disposed while a MoveNext is in flight");DisposeAsyncdoes not. - Failure scenario: The documented usage is "Dispose to end the call". A consumer task sits in
await foreach (var e in stream.ReadAllAsync())waiting for the next event. A shutdown path on another task callsawait stream.DisposeAsync(). It throwsNotSupportedExceptionout of the dispose (and out of anyawait usingscope), which most shutdown code does not expect. Thefinallystill disposes_lifetimewhile the reader is unwinding. The underlying call is cancelled, so nothing leaks, but shutdown reports a spurious failure. - Suggested fix: Track the in-flight
MoveNextAsynctask (or a reader-completionTaskCompletionSource) inReadAllAsync; inDisposeAsync, afterCancelAsync, await it (swallowing its exception) before_enumerator.DisposeAsync(), mirroringOpenAsync. - Test idea: Fake transport whose stream awaits a
TaskCompletionSourcecreated withRunContinuationsAsynchronouslyand cancelled by token registration. StartReadAllAsyncon one task, callDisposeAsyncfrom another, assert it completes without throwing and the reader ends withOperationCanceledException.
CDN-004 — No HTTP/2 keepalive; deadline-less streams hang on a half-open connection
- Severity: Medium. Category: Bug. Confidence: Plausible (absence of configuration confirmed; hang not reproduced).
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClient.cs:398-403,GalaxyRepositoryClient.cs:538-543(handler sets onlyConnectTimeoutand TLS),MxGatewayClientOptions.cs:56(StreamTimeoutdefaults to null, so streams carry no deadline). - Description: The
SocketsHttpHandlerleavesKeepAlivePingDelay,KeepAlivePingTimeoutandKeepAlivePingPolicyat their defaults (pings disabled). A server-streaming call only reads, so when the peer disappears without a FIN/RST there is no outbound data whose retransmission would fail. Nothing ever completes the pendingMoveNext. - Failure scenario: The gateway host loses power, or a firewall silently drops the idle flow. A client inside
await foreachoverStreamEventsAsync,StreamAlarmsAsyncorWatchDeployEventsAsyncsees no events and no exception, indefinitely. Its reconnect loop never runs because nothing ended. Tag values go stale with no signal. The only escape is theCreate(GrpcChannel, ...)overload with a caller-configured handler;Create(options)offers no knob. - Suggested fix: Set
KeepAlivePingDelay(for example 30 s),KeepAlivePingTimeout(for example 10 s) andKeepAlivePingPolicy = HttpKeepAlivePingPolicy.Alwayson the handler, optionally exposed throughMxGatewayClientOptions. - Test idea: Unit test on
CreateHttpHandlerForTestsasserting the ping settings. Integration: start a stream through a TCP proxy, black-hole the proxy, assert the stream faults within ping delay + timeout.
CDN-005 — MxGatewaySession.DisposeAsync can block for about a minute and can throw
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs:1713-1729,:44-70(CloseAsync),MxGatewayClient.cs:188-198and:374-388(close goes through the retry pipeline),MxGatewayClientRetryOptions.csdefaults (MaxAttempts = 2,MaxDelay = 2 s),MxGatewayClientOptions.cs(DefaultCallTimeout = 30 s). - Description:
DisposeAsynccallsCloseAsync()with no cancellation token.CloseSessionRawAsyncis retried onUnavailable/DeadlineExceeded, each attempt with its own 30 s deadline. The catch filter coversMxGatewayException,ObjectDisposedExceptionandRpcExceptionbut notOperationCanceledException. - Failure scenario: (1) The gateway is unreachable through a black-holing network path.
await using var session = ...leaving scope waits 30 s for attempt one, backs off, waits 30 s for attempt two: about 62 s before the application can continue shutting down. (2) The gateway is shutting down while the close is in flight and answersCancelled; via CDN-001 that becomesOperationCanceledException, which escapes the filter, soDisposeAsyncthrows and masks whatever exception was already propagating through theawait using. - Suggested fix: Use a short bounded token for the dispose-time close (for example 5 s, single attempt) and add
OperationCanceledExceptionto the swallowed set. - Test idea: Fake transport whose
CloseSessionAsyncnever completes until its deadline; assertDisposeAsyncreturns within the bound. Second case: transport throwsOperationCanceledException; assert dispose does not throw.
CDN-006 — Owned SocketsHttpHandler is never disposed with the channel
- Severity: Low. Category: Performance (resource leak). Confidence: Confirmed.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClient.cs:79-88and:317-331,GalaxyRepositoryClient.cs:87-95and:459-473; pinned CA atMxGatewayClient.cs:415,GalaxyRepositoryClient.cs:555. - Description:
Create(options)builds aSocketsHttpHandlerand passes it asGrpcChannelOptions.HttpHandlerwithout settingDisposeHttpClient = true. Grpc.Net.Client only disposes a caller-supplied handler when that flag is set, so_channel.Dispose()leaves the handler and its connection pool alive. TheX509Certificate2 trustedRootcaptured by the validation callback is also never disposed. - Failure scenario: An application that recreates the client on each reconnect attempt (a common recovery pattern) leaves one handler, its HTTP/2 connection and its pool timer behind per attempt until the pool's idle timeout scavenges the socket. During a long outage with a tight reconnect loop this accumulates sockets and handles on both the client and the gateway.
- Suggested fix: Set
DisposeHttpClient = trueon the owned-channel path (or keep the handler and dispose it inDisposeAsync), and disposetrustedRootwith it. - Test idea: Create and dispose a client against a loopback listener; assert the server side observes the connection close promptly after
DisposeAsync.
CDN-007 — ResourceExhausted is retried as transient
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientRetryPolicy.cs:87-92; applied to every Galaxy unary call (GalaxyRepositoryClient.csExecuteSafeUnaryAsync) and toCloseSession/Ping/GetSessionState/GetWorkerInfo. - Description: Every source of
ResourceExhaustedreachable on the retried calls is deterministic over the retry window: the auth failure limiter (src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:133-135, "Too many authentication attempts"), and Grpc.Net.Client's own "received message exceeds the maximum configured message size". - Failure scenario:
DiscoverHierarchyAsyncrequests pages of 5000 objects. On a large Galaxy a page with attributes exceedsMaxGrpcMessageBytes(16 MiB). The client downloads up to 16 MiB, fails withResourceExhausted, waits, then makes the gateway run the same SQL page and re-download it before failing identically. With a raisedMaxAttemptsthe waste multiplies. For the auth limiter, the retry just sends another request into the throttle window. - Suggested fix: Drop
ResourceExhaustedfromIsTransientStatus, or retry it only when the trailer reason marks it as transient. - Test idea: Fake transport returning
ResourceExhaustedonce; assert exactly one attempt is made.
CDN-008 — RegisterAsync / AddItemAsync / AddItem2Async dereference a null ReturnValue
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs:84,:126,:177. - Description: These three still use
reply.X?.Handle ?? reply.ReturnValue.Int32Value.ReturnValueis a message field and is null when unset, so an OK reply with neither the typed payload nor a return value throwsNullReferenceException; a return value of a different kind silently yields0.AddBufferedItemAsync,AuthenticateUserAsyncandArchestraUserToIdAsyncwere moved toResolveInt32Result(:1408-1427), whose own comment calls the NRE "historical"; the three most-used helpers were not. - Failure scenario: A worker/gateway version skew returns an OK
Registerreply without theregisterpayload. The caller gets aNullReferenceExceptionwith no session or correlation context instead ofMxGatewayMalformedReplyException, or a handle of0that is then used forAddItem. - Suggested fix: Route all three through
ResolveInt32Result. - Test idea: Fake transport returning
MxCommandReply { ProtocolStatus = Ok }for Register/AddItem/AddItem2; assertMxGatewayMalformedReplyException.
CDN-009 — CLI: global 30 s cancellation hits streaming and bench commands; OperationCanceledException escapes unhandled
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs:467-482(CreateCancellation: onlygalaxy-watch/galaxy-browseare exempt),:176(top-level catch excludesOperationCanceledException),:1474and:1543(stream commands swallow it),:1145-1260(bench),Program.cs:3(no catch). - Description: Every command other than
galaxy-watch/galaxy-browseruns under aCancellationTokenSourcecancelled after--timeout(default 30 s). (a)stream-eventsandstream-alarmswithout--timeoutstop after 30 s and exit 0 with no message, indistinguishable from a server-ended stream. (b)bench-read-bulkdefaults to 3 s warm-up + 30 s measurement, so with default arguments it is always cancelled mid-run;scripts/bench-read-bulk.ps1:123-125works around this by passing a larger--timeout. (c) For any non-stream command theOperationCanceledExceptionis excluded by the only catch inRunCoreAsyncandProgram.cshas none, so the process dies with an unhandled-exception stack trace instead of a redacted error line and exit code 1.--jsoncallers get no JSON error object. - Failure scenario:
mxgw-dotnet stream-events --session-id Xused as a long-running tail silently ends after 30 s.mxgw-dotnet read-bulk ... --timeout 2sagainst a slow gateway crashes withUnhandled exception. System.OperationCanceledExceptionand a runtime abort exit code. - Suggested fix: Add
stream-events,stream-alarmsandbench-read-bulkto the long-running set (or derive the bench budget from its duration). CatchOperationCanceledExceptionat the top level and emit a "timed out after " error with exit code 1. - Test idea: CLI test with a fake client whose
InvokeAsyncnever completes and--timeout 100ms; assert exit code 1 and a JSON error on stderr rather than a thrown exception.
CDN-010 — CLI: --value text is redacted from every error message
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs:183-189,MxGatewayCliSecretRedactor.cs(ordinalReplaceof each secret). - Description: The top-level error handler passes
arguments.GetOptional("value")as a secret for all commands, not onlywrite-secured*. Any occurrence of the value string in the error message is replaced with[redacted], with no minimum length. - Failure scenario:
mxgw-dotnet write --value 0 ...fails withMXAccess command failed. kind=Write; hresult=0x80004005; .... The operator seeshresult=[redacted]x8[redacted][redacted][redacted]4[redacted][redacted]5and a session id with every0replaced. The HRESULT, the one thing needed to diagnose the failure, is destroyed. - Suggested fix: Redact
--valueonly for the secured-write commands, and skip redaction (or redact whole tokens only) for values shorter than a few characters. - Test idea: CLI test:
write --value 0with a fake client throwing anMxAccessExceptionwhose message contains0x80004005; assert the HRESULT text survives.
CDN-011 — CLI batch mode builds a new channel per line
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location:
clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs:98(client created insideRunCoreAsync),:216-280(RunBatchAsynccallsRunCoreAsyncper line),MxGatewayCliClientAdapter.cs:19-20(Galaxy commands create a secondGrpcChannelinstead of sharing the first). - Description: Each batch line constructs a
GrpcChannel+SocketsHttpHandler, performs a fresh TCP/TLS/HTTP/2 handshake, and disposes the channel (leaving the handler behind, CDN-006). Galaxy commands open a second independent channel to the same endpoint. - Failure scenario: The cross-language e2e harness drives hundreds of commands through
batch. Each pays a full connection setup, which dominates per-command latency and defeats the purpose of a persistent batch process. - Suggested fix: Cache the client in
RunBatchAsynckeyed by the resolved connection options and reuse it across lines; build the Galaxy client withGalaxyRepositoryClient.Create(channel, options)over the same channel. - Test idea: Batch test with a counting
clientFactory; assert one client for N lines with identical connection options.
Go
CGO-001 — No keepalive; deadline-less streams hang on a half-open connection
- Severity: Medium. Category: Bug. Confidence: Plausible (absence of configuration confirmed; hang not reproduced).
- Location:
clients/go/mxgateway/client.go:62-67,clients/go/mxgateway/galaxy.go:98-103(dial options: credentials + two interceptors only),client.go:169-180(StreamEventsRawapplies no deadline, by design). - Description: No
grpc.WithKeepaliveParamsis set, so grpc-go sends no HTTP/2 pings. A server-streamingRecvon a connection whose peer vanished without FIN/RST never returns. - Failure scenario: Same as CDN-004. The receive goroutine in
subscribeEventsAfter(session.go:1119-1148) blocks instream.Recv()forever; the consumer's channel neither delivers nor closes, so a reconnect loop built on "channel closed orErrset" never triggers. Callers can work around it throughOptions.DialOptions, but the default is the unsafe one. - Suggested fix: Add a default
grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: 30 * time.Second, Timeout: 10 * time.Second, PermitWithoutStream: false})ahead ofopts.DialOptionsso callers can still override. Confirm the gateway's Kestrel ping policy tolerates the interval. - Test idea: Stream through a TCP proxy, black-hole it, assert the subscription delivers an
Errresult within Time + Timeout.
CGO-002 — API key is attached only by dial-time interceptors
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/go/mxgateway/client.go:62-67and:79-85,clients/go/mxgateway/galaxy.go:98-103and:116-122,clients/go/mxgateway/auth.go:12-22. - Description: Two ways to lose the
authorizationheader without any error at construction time. (1)NewClient(conn, opts)/NewGalaxyClient(conn, opts)storeoptsbut never useopts.APIKey; the header is added only by the interceptorsDialinstalls. (2)Dialappendsopts.DialOptionsafter its owngrpc.WithUnaryInterceptor/grpc.WithStreamInterceptor. Those two options are last-wins in grpc-go, so a caller passing its own single interceptor (tracing, metrics) replaces the auth interceptor. - Failure scenario: A service shares one
*grpc.ClientConnand callsmxgateway.NewClient(conn, mxgateway.Options{APIKey: key}). Every RPC fails withUnauthenticatedalthough a key was supplied; repeated failures also feed the gateway's per-peer auth failure limiter. LikewiseOptions{APIKey: key, DialOptions: []grpc.DialOption{grpc.WithUnaryInterceptor(otelInterceptor)}}authenticates streams but not unary calls. - Suggested fix: Install auth with
grpc.WithChainUnaryInterceptor/grpc.WithChainStreamInterceptor(orgrpc.WithPerRPCCredentials) so it composes with caller interceptors, and haveClient/GalaxyClientcallauthContext(ctx, c.opts.APIKey)themselves when constructed throughNewClient(guarding against double-append on theDialpath). - Test idea: bufconn server asserting the
authorizationmetadata; coverNewClient(conn, Options{APIKey})andDialwith a callerWithUnaryInterceptor.
CGO-003 — Stream ended by a deadline or a server-sent Canceled closes the channel with no error
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/go/mxgateway/session.go:1138-1140,clients/go/mxgateway/galaxy.go:253-258. Server origins ofCanceled:src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs:1077-1081,:1142. - Description: The receive goroutine returns silently when
err == io.EOF || status.Code(err) == codes.Canceled || streamCtx.Err() != nil. Two of those are not caller cancellations: aCanceledstatus produced by the gateway (it maps any server-side cancellation andGatewayShutdowntoCanceled), and a parent-context deadline (streamCtx.Err()isDeadlineExceeded). All three look identical to the consumer: a closed channel with noErrresult, the same as a clean server end afterCloseSession. - Failure scenario: A caller derives
ctxwith a 30 s timeout intended for "the subscribe call" and passes it toSubscribeEvents. After 30 s the events channel closes with no error. The consumer logs "stream ended" and treats the session as closed. In the gateway-shutdown case the correct reaction is to reconnect; in the clean-EOF case the session is gone. The consumer cannot tell which without probing. - Suggested fix: Return silently only when
errors.Is(streamCtx.Err(), context.Canceled). Deliver a terminalEventResult{Err: &GatewayError{...}}forDeadlineExceededand for aCanceledstatus received whilestreamCtxis still live. - Test idea: bufconn server that ends
StreamEventswithstatus.Error(codes.Canceled, ...); assert a terminalErrresult. Second case: parent context with a short deadline; assert anErrwrappingcontext.DeadlineExceeded.
CGO-004 — Stream context is never cancelled on EOF / terminal error
- Severity: Low. Category: Performance (leak). Confidence: Confirmed.
- Location:
clients/go/mxgateway/session.go:1105-1155(goroutine exits at:1139and:1146without callingcancel),:1087-1093(EventsAfterdiscards theEventSubscription, the only holder ofcancel). - Description:
subscribeEventsAftercreatesstreamCtx, cancel := context.WithCancel(ctx).cancelruns only fromEventSubscription.Closeor the slow-consumer branch. When the stream ends by EOF or a terminal error, the goroutine returns without cancelling, so the child context stays registered in the parent's children set until the parent is cancelled. ForEvents/EventsAfterthe caller has no handle to cancel at all. - Failure scenario: A long-running collector holds one cancellable root context for its lifetime and reconnects with
EventsAfter(rootCtx, lastSeq)whenever the stream drops. Each reconnect leaves onecancelCtx(and whatever it references) attached torootCtx. Over weeks of flapping this is unbounded growth and a progressively slower root cancel. - Suggested fix:
defer cancel()at the top of the receive goroutine. - Test idea: Parent
context.WithCancel; open and server-EOF N streams viaEvents; assert thestreamCtxpassed to a fakeStreamEventsRawreportsErr() != nilafter each stream ends.
CGO-005 — dialConnected waits the full timeout and discards the cause
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/go/mxgateway/client.go:285-298. - Description: The loop returns only on
Ready,Shutdown, or context expiry.TransientFailureis treated like any other state, so a connection that fails instantly (connection refused, TLS verification failure, badServerNameOverride) keeps cycling through backoff untilDialTimeout(default 10 s) elapses. The returned error isctx.Err(); the transport's actual error is never surfaced. - Failure scenario: An operator runs
mxgw-go ping -ca-cert wrong.pem .... The command hangs 10 s and printsmxgateway: dial failed: context deadline exceeded. Nothing indicates a certificate problem. In batch mode every line pays the same 10 s. - Suggested fix: On
TransientFailure, either fail fast or keep waiting but remember it and, on expiry, return an error that includes the last connection error (for example by issuing a cheap RPC withgrpc.WaitForReady(false)and returning its status). - Test idea:
Dialto a closed local port with a 5 s timeout; assert it returns well under the timeout, or at least that the error text contains "connection refused".
CGO-006 — WatchDeployEvents closes errs before events
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/go/mxgateway/galaxy.go:238-265(defer close(events)thendefer close(errs), soerrscloses first),clients/go/cmd/mxgw-go/main.go:1716-1722. - Description: On teardown the goroutine closes
errsand thenevents, while up to 16 events may still be buffered inevents. A consumer selecting on both channels can observeerrsclosed (or the terminal error) before it has drainedevents. The CLI does exactly that:case streamErr, ok := <-errs: if !ok { return nil }. - Failure scenario: The gateway completes the deploy stream right after emitting events.
galaxy-watchhas unread events buffered;selectpicks the closederrscase and returns, so the last events are never printed. A library consumer written the same way silently misses the final deploy notification. - Suggested fix: Close
eventsfirst anderrslast (swap the defers), document "drainevents, then readerrs", and in the CLI seterrs = nilwhen it closes rather than returning. A single result channel likeEventResultwould remove the ambiguity. - Test idea: Fake stream returning three events then
io.EOFwhile the consumer is not yet reading; run the CLI loop and assert all three are printed.
CGO-007 — Register / AddItem / AddItem2 return handle 0 on a payload-less reply
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/go/mxgateway/session.go:143-146,:199-202,:228-231. - Description: These fall back to
reply.GetReturnValue().GetInt32Value(), which is0when the return value is absent or not an int32.AuthenticateUser,ArchestrAUserToIdandAddBufferedItem(:877-886,:918-927,:953-962) check the oneof kind and returnMalformedReplyError; the three most-used helpers do not. - Failure scenario: Version skew produces an OK
AddItemreply without theadd_itempayload. The caller receives item handle0andnilerror, then advises and writes against handle0. - Suggested fix: Apply the same kind check and
MalformedReplyErrorto all three. - Test idea: Fake
Invokereturning an OK reply with no payload for each command; asserterrors.As(err, *MalformedReplyError).
CGO-008 — CLI: blocking dial per batch line; bench loop spins on failure
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location:
clients/go/cmd/mxgw-go/main.go:1478-1505(runBatchdispatches each line throughrunWithIO),:1306-1321(dialForCommandin every command),:817-819(warm-up loop) and:829-837(steady-state loop). - Description: (a) Every batch line performs
mxgateway.Dial, which blocks until the channel is READY (TCP + TLS + HTTP/2 preface), then closes the connection. (b)runBenchReadBulkcounts a failedReadBulkand immediately loops; the warm-up loop ignores errors entirely. - Failure scenario: (a) Harness-driven batch runs pay a full handshake per command, and 10 s per command when the gateway is down (CGO-005). (b) The gateway drops mid-benchmark;
ReadBulkfails in microseconds withUnavailable, and the loop issues failing RPCs as fast as the CPU allows for the rest of the window, producing a meaningless latency sample and a burst of load when the gateway returns. - Suggested fix: Cache the dialed client across batch lines keyed by resolved options. In the bench loops, stop (or sleep briefly) after consecutive transport failures.
- Test idea: Batch test with a counting dial hook asserting one dial for N lines; bench test against a closed endpoint asserting the call count stays bounded.