Files
mxaccessgw/code-reviews/2026-12-02-perf-bugs/clients-dotnet-go.md
T

34 KiB

Clients (.NET / Go) — Bugs and Performance Review

  • Date: 2026-12-02
  • HEAD: 54367e74
  • Scope: clients/dotnet/ (ZB.MOM.WW.MxGateway.Client library + ZB.MOM.WW.MxGateway.Client.Cli) and clients/go/ (mxgateway package + 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-side OperationCanceledException), :1142 (WorkerClientErrorCode.GatewayShutdown => StatusCode.Cancelled), src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs:491-494 and :1142-1146 (pending commands completed with GatewayShutdown when the worker client is closed or disposed).
  • Description: MapRpcException returns an OperationCanceledException when cancellationToken.IsCancellationRequested || exception.StatusCode == StatusCode.Cancelled. The second arm fires for a status the gateway itself produced. The server completes every pending command with GatewayShutdown when a session's worker client is closed (session closed by another caller, dashboard Close/Kill, lease reaper, gateway shutdown), and that maps to gRPC Cancelled. The exception is also constructed with the caller's token, which is not cancelled. DotnetClientDesign.md:157-158 states the intended rule: surface OperationCanceledException "only when the caller initiated cancellation".
  • Failure scenario: A client has WriteAsync in flight when an administrator kills the session from the dashboard, or the gateway service is stopped for a deploy. The call throws OperationCanceledException. 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 bypasses MxGatewaySession.DisposeAsync's catch filter (CDN-005) and the CLI's top-level handler (CDN-009).
  • Suggested fix: Map to OperationCanceledException only when the caller's token is cancelled. Map a Cancelled status with a live token to MxGatewayException (or a typed "gateway shutting down / session closed" subtype) keeping the RpcException as inner.
  • Test idea: Fake transport call that throws RpcException(Status(Cancelled)) with a non-cancelled token; assert InvokeAsync throws MxGatewayException, not OperationCanceledException. 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 only Unauthenticated, PermissionDenied, ResourceExhausted), MxCommandReplyExtensions.cs:59-66 (the only place MxGatewaySessionException is created). Server: src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs:1106-1107 (SessionNotFound => StatusCode.NotFound, SessionNotReady => StatusCode.FailedPrecondition).
  • Description: MxGatewaySessionException is built only from a reply whose ProtocolStatus.Code is SessionNotFound or SessionNotReady. The gateway never returns those codes in a reply: the MxAccessGrpcMapper.SessionNotFound/SessionNotReady helpers have no callers in the server, and Invoke, StreamEvents and CloseSession all throw RpcException(NotFound) / RpcException(FailedPrecondition) instead. MapRpcException sends both to the base MxGatewayException. 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 gets NotFound. Its recovery code catch (MxGatewaySessionException) { reopen and re-subscribe } never runs; the error lands in the generic catch (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).StatusCode out by hand.
  • Suggested fix: In MapRpcException, map NotFound and FailedPrecondition to MxGatewaySessionException (carrying the status detail and inner RpcException). Consider exposing the gRPC StatusCode on MxGatewayException so callers do not need the inner exception.
  • Test idea: Fake transport throwing RpcException(Status(NotFound, "Session x was not found.")) from InvokeAsync and from the event stream; assert MxGatewaySessionException.

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-flight MoveNextAsync), :95 (_enumerator is the compiler-generated iterator from GrpcMxGatewayClientTransport.StreamEventsAsync, GrpcMxGatewayClientTransport.cs:82-113).
  • Description: DisposeAsync cancels _lifetime and immediately calls _enumerator.DisposeAsync(). A compiler-generated async iterator throws NotSupportedException from DisposeAsync while a MoveNextAsync is still pending. CancelAsync only 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 its await. OpenAsync in 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"); DisposeAsync does 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 calls await stream.DisposeAsync(). It throws NotSupportedException out of the dispose (and out of any await using scope), which most shutdown code does not expect. The finally still disposes _lifetime while the reader is unwinding. The underlying call is cancelled, so nothing leaks, but shutdown reports a spurious failure.
  • Suggested fix: Track the in-flight MoveNextAsync task (or a reader-completion TaskCompletionSource) in ReadAllAsync; in DisposeAsync, after CancelAsync, await it (swallowing its exception) before _enumerator.DisposeAsync(), mirroring OpenAsync.
  • Test idea: Fake transport whose stream awaits a TaskCompletionSource created with RunContinuationsAsynchronously and cancelled by token registration. Start ReadAllAsync on one task, call DisposeAsync from another, assert it completes without throwing and the reader ends with OperationCanceledException.

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 only ConnectTimeout and TLS), MxGatewayClientOptions.cs:56 (StreamTimeout defaults to null, so streams carry no deadline).
  • Description: The SocketsHttpHandler leaves KeepAlivePingDelay, KeepAlivePingTimeout and KeepAlivePingPolicy at 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 pending MoveNext.
  • Failure scenario: The gateway host loses power, or a firewall silently drops the idle flow. A client inside await foreach over StreamEventsAsync, StreamAlarmsAsync or WatchDeployEventsAsync sees 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 the Create(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) and KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always on the handler, optionally exposed through MxGatewayClientOptions.
  • Test idea: Unit test on CreateHttpHandlerForTests asserting 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-198 and :374-388 (close goes through the retry pipeline), MxGatewayClientRetryOptions.cs defaults (MaxAttempts = 2, MaxDelay = 2 s), MxGatewayClientOptions.cs (DefaultCallTimeout = 30 s).
  • Description: DisposeAsync calls CloseAsync() with no cancellation token. CloseSessionRawAsync is retried on Unavailable / DeadlineExceeded, each attempt with its own 30 s deadline. The catch filter covers MxGatewayException, ObjectDisposedException and RpcException but not OperationCanceledException.
  • 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 answers Cancelled; via CDN-001 that becomes OperationCanceledException, which escapes the filter, so DisposeAsync throws and masks whatever exception was already propagating through the await using.
  • Suggested fix: Use a short bounded token for the dispose-time close (for example 5 s, single attempt) and add OperationCanceledException to the swallowed set.
  • Test idea: Fake transport whose CloseSessionAsync never completes until its deadline; assert DisposeAsync returns within the bound. Second case: transport throws OperationCanceledException; 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-88 and :317-331, GalaxyRepositoryClient.cs:87-95 and :459-473; pinned CA at MxGatewayClient.cs:415, GalaxyRepositoryClient.cs:555.
  • Description: Create(options) builds a SocketsHttpHandler and passes it as GrpcChannelOptions.HttpHandler without setting DisposeHttpClient = 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. The X509Certificate2 trustedRoot captured 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 = true on the owned-channel path (or keep the handler and dispose it in DisposeAsync), and dispose trustedRoot with 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.cs ExecuteSafeUnaryAsync) and to CloseSession / Ping / GetSessionState / GetWorkerInfo.
  • Description: Every source of ResourceExhausted reachable 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: DiscoverHierarchyAsync requests pages of 5000 objects. On a large Galaxy a page with attributes exceeds MaxGrpcMessageBytes (16 MiB). The client downloads up to 16 MiB, fails with ResourceExhausted, waits, then makes the gateway run the same SQL page and re-download it before failing identically. With a raised MaxAttempts the waste multiplies. For the auth limiter, the retry just sends another request into the throttle window.
  • Suggested fix: Drop ResourceExhausted from IsTransientStatus, or retry it only when the trailer reason marks it as transient.
  • Test idea: Fake transport returning ResourceExhausted once; 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. ReturnValue is a message field and is null when unset, so an OK reply with neither the typed payload nor a return value throws NullReferenceException; a return value of a different kind silently yields 0. AddBufferedItemAsync, AuthenticateUserAsync and ArchestraUserToIdAsync were moved to ResolveInt32Result (: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 Register reply without the register payload. The caller gets a NullReferenceException with no session or correlation context instead of MxGatewayMalformedReplyException, or a handle of 0 that is then used for AddItem.
  • Suggested fix: Route all three through ResolveInt32Result.
  • Test idea: Fake transport returning MxCommandReply { ProtocolStatus = Ok } for Register/AddItem/AddItem2; assert MxGatewayMalformedReplyException.

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: only galaxy-watch / galaxy-browse are exempt), :176 (top-level catch excludes OperationCanceledException), :1474 and :1543 (stream commands swallow it), :1145-1260 (bench), Program.cs:3 (no catch).
  • Description: Every command other than galaxy-watch / galaxy-browse runs under a CancellationTokenSource cancelled after --timeout (default 30 s). (a) stream-events and stream-alarms without --timeout stop after 30 s and exit 0 with no message, indistinguishable from a server-ended stream. (b) bench-read-bulk defaults to 3 s warm-up + 30 s measurement, so with default arguments it is always cancelled mid-run; scripts/bench-read-bulk.ps1:123-125 works around this by passing a larger --timeout. (c) For any non-stream command the OperationCanceledException is excluded by the only catch in RunCoreAsync and Program.cs has none, so the process dies with an unhandled-exception stack trace instead of a redacted error line and exit code 1. --json callers get no JSON error object.
  • Failure scenario: mxgw-dotnet stream-events --session-id X used as a long-running tail silently ends after 30 s. mxgw-dotnet read-bulk ... --timeout 2s against a slow gateway crashes with Unhandled exception. System.OperationCanceledException and a runtime abort exit code.
  • Suggested fix: Add stream-events, stream-alarms and bench-read-bulk to the long-running set (or derive the bench budget from its duration). Catch OperationCanceledException at the top level and emit a "timed out after " error with exit code 1.
  • Test idea: CLI test with a fake client whose InvokeAsync never 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 (ordinal Replace of each secret).
  • Description: The top-level error handler passes arguments.GetOptional("value") as a secret for all commands, not only write-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 with MXAccess command failed. kind=Write; hresult=0x80004005; .... The operator sees hresult=[redacted]x8[redacted][redacted][redacted]4[redacted][redacted]5 and a session id with every 0 replaced. The HRESULT, the one thing needed to diagnose the failure, is destroyed.
  • Suggested fix: Redact --value only 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 0 with a fake client throwing an MxAccessException whose message contains 0x80004005; 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 inside RunCoreAsync), :216-280 (RunBatchAsync calls RunCoreAsync per line), MxGatewayCliClientAdapter.cs:19-20 (Galaxy commands create a second GrpcChannel instead 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 RunBatchAsync keyed by the resolved connection options and reuse it across lines; build the Galaxy client with GalaxyRepositoryClient.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 (StreamEventsRaw applies no deadline, by design).
  • Description: No grpc.WithKeepaliveParams is set, so grpc-go sends no HTTP/2 pings. A server-streaming Recv on 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 in stream.Recv() forever; the consumer's channel neither delivers nor closes, so a reconnect loop built on "channel closed or Err set" never triggers. Callers can work around it through Options.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 of opts.DialOptions so 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 Err result 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-67 and :79-85, clients/go/mxgateway/galaxy.go:98-103 and :116-122, clients/go/mxgateway/auth.go:12-22.
  • Description: Two ways to lose the authorization header without any error at construction time. (1) NewClient(conn, opts) / NewGalaxyClient(conn, opts) store opts but never use opts.APIKey; the header is added only by the interceptors Dial installs. (2) Dial appends opts.DialOptions after its own grpc.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.ClientConn and calls mxgateway.NewClient(conn, mxgateway.Options{APIKey: key}). Every RPC fails with Unauthenticated although a key was supplied; repeated failures also feed the gateway's per-peer auth failure limiter. Likewise Options{APIKey: key, DialOptions: []grpc.DialOption{grpc.WithUnaryInterceptor(otelInterceptor)}} authenticates streams but not unary calls.
  • Suggested fix: Install auth with grpc.WithChainUnaryInterceptor / grpc.WithChainStreamInterceptor (or grpc.WithPerRPCCredentials) so it composes with caller interceptors, and have Client/GalaxyClient call authContext(ctx, c.opts.APIKey) themselves when constructed through NewClient (guarding against double-append on the Dial path).
  • Test idea: bufconn server asserting the authorization metadata; cover NewClient(conn, Options{APIKey}) and Dial with a caller WithUnaryInterceptor.

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 of Canceled: 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: a Canceled status produced by the gateway (it maps any server-side cancellation and GatewayShutdown to Canceled), and a parent-context deadline (streamCtx.Err() is DeadlineExceeded). All three look identical to the consumer: a closed channel with no Err result, the same as a clean server end after CloseSession.
  • Failure scenario: A caller derives ctx with a 30 s timeout intended for "the subscribe call" and passes it to SubscribeEvents. 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 terminal EventResult{Err: &GatewayError{...}} for DeadlineExceeded and for a Canceled status received while streamCtx is still live.
  • Test idea: bufconn server that ends StreamEvents with status.Error(codes.Canceled, ...); assert a terminal Err result. Second case: parent context with a short deadline; assert an Err wrapping context.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 :1139 and :1146 without calling cancel), :1087-1093 (EventsAfter discards the EventSubscription, the only holder of cancel).
  • Description: subscribeEventsAfter creates streamCtx, cancel := context.WithCancel(ctx). cancel runs only from EventSubscription.Close or 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. For Events / EventsAfter the 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 one cancelCtx (and whatever it references) attached to rootCtx. 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 via Events; assert the streamCtx passed to a fake StreamEventsRaw reports Err() != nil after 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. TransientFailure is treated like any other state, so a connection that fails instantly (connection refused, TLS verification failure, bad ServerNameOverride) keeps cycling through backoff until DialTimeout (default 10 s) elapses. The returned error is ctx.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 prints mxgateway: 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 with grpc.WaitForReady(false) and returning its status).
  • Test idea: Dial to 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) then defer close(errs), so errs closes first), clients/go/cmd/mxgw-go/main.go:1716-1722.
  • Description: On teardown the goroutine closes errs and then events, while up to 16 events may still be buffered in events. A consumer selecting on both channels can observe errs closed (or the terminal error) before it has drained events. 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-watch has unread events buffered; select picks the closed errs case 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 events first and errs last (swap the defers), document "drain events, then read errs", and in the CLI set errs = nil when it closes rather than returning. A single result channel like EventResult would remove the ambiguity.
  • Test idea: Fake stream returning three events then io.EOF while 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 is 0 when the return value is absent or not an int32. AuthenticateUser, ArchestrAUserToId and AddBufferedItem (:877-886, :918-927, :953-962) check the oneof kind and return MalformedReplyError; the three most-used helpers do not.
  • Failure scenario: Version skew produces an OK AddItem reply without the add_item payload. The caller receives item handle 0 and nil error, then advises and writes against handle 0.
  • Suggested fix: Apply the same kind check and MalformedReplyError to all three.
  • Test idea: Fake Invoke returning an OK reply with no payload for each command; assert errors.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 (runBatch dispatches each line through runWithIO), :1306-1321 (dialForCommand in 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) runBenchReadBulk counts a failed ReadBulk and 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; ReadBulk fails in microseconds with Unavailable, 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.