25 KiB
25 KiB
Clients (Rust / Java / Python) — Bugs and Performance Review
- Date: 2026-12-02
- HEAD:
54367e74 - Scope:
clients/rust/(src + crates),clients/java/(client + CLI),clients/python/src/zb_mom_ww_mxgateway{,_cli}. Generated code, build output and tests excluded (tests read only to confirm behaviour). - Method: read-only source review. Nothing was built or executed; "Confirmed" means the defect is visible in the cited code, "Plausible" means the code path is confirmed but the runtime impact depends on library/server behaviour that was not reproduced.
None of the three clients implements automatic reconnect: all expose after_worker_sequence resume and surface ReplayGap as a typed item, and that mapping is correct in all three (Rust EventItem::from_event, Java MxEventStreamItem, Python _surface_replay_gaps). No duplicate/lost-event defect was found in the client-side resume plumbing itself. The findings below are about liveness, cleanup, error mapping and secret hygiene around it.
Summary
| ID | Severity | Category | Confidence | Title |
|---|---|---|---|---|
| CRS-001 | Medium | Bug | Plausible | No HTTP/2 or TCP keepalive on the tonic channel; deadline-less streams hang forever on a half-open connection |
| CRS-002 | Low | Bug | Confirmed | attach_secrets scrubs only Error::MxAccess; Error::Command from secured writes / authenticate_user keeps the unscrubbed reply |
| CRS-003 | Low | Bug | Plausible | Raw tonic::Status is retained and printed unredacted (Error::Status Display, Debug of every status variant) |
| CRS-004 | Low | Performance | Confirmed | CLI batch mode dials a new channel for every line |
| CJV-001 | Medium | Bug | Confirmed | MxGatewayClient.close() only calls shutdown(); open streams and their blocked readers survive it |
| CJV-002 | Medium | Bug | Confirmed | GalaxyRepositoryClient ignores the lenient-TLS default that MxGatewayClient honours |
| CJV-003 | Medium | Bug | Plausible | No keepalive on the Netty channel; same half-open hang as CRS-001 |
| CJV-004 | Low | Bug | Confirmed | MxEventStream / DeployEventStream rethrow raw StatusRuntimeException, bypassing typed mapping and redaction |
| CJV-005 | Low | Bug | Confirmed | DeployEventStream.take() does not cancel the RPC on interrupt |
| CJV-006 | Low | Bug | Confirmed | Typed helpers return 0 / empty list when the reply lacks the expected payload |
| CJV-007 | Low | Performance | Plausible | SecureRandom used for every command correlation id |
| CPY-001 | Medium | Bug | Confirmed | Enum .Name() raises ValueError on unknown values while building typed errors |
| CPY-002 | Medium | Bug | Plausible | No keepalive channel options; same half-open hang as CRS-001 |
| CPY-003 | Low | Bug | Confirmed | map_rpc_error drops the status code and does not redact credentials |
| CPY-004 | Low | Bug | Confirmed | register / add_item / add_item2 return 0 on a reply without the payload |
| CPY-005 | Low | Performance | Confirmed | CLI batch mode runs a new event loop, channel and TOFU TLS probe per line |
| CPY-006 | Low | Bug | Plausible | smoke advises before attaching the event stream, so the initial value can be missed |
Rust
CRS-001 — No HTTP/2 or TCP 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/rust/src/client.rs:181-194,clients/rust/src/galaxy.rs:176-189,clients/rust/src/options.rs:47-49(stream_timeout: Nonedefault). - Description: The
Endpointis configured withconnect_timeoutand TLS only. Nohttp2_keep_alive_interval,keep_alive_timeout,keep_alive_while_idleortcp_keepaliveis set, and streaming RPCs carry no deadline unless the caller opts intowith_stream_timeout. A grep across all three clients finds no keepalive setting anywhere. - Failure scenario: A consumer holds
Session::events()on slow-changing tags. A stateful firewall/NAT idles the flow out, or the gateway host loses power, without a FIN/RST reaching the client.stream.next().awaitnever resolves and never errors, so the consumer never reaches its reconnect/events_afterpath. Meanwhile the gateway's 30 s detach grace and 300 s replay retention expire, so by the time anything notices, the session and its replay history are gone. Unary calls are bounded bycall_timeout; streams are not. - Suggested fix: Set
http2_keep_alive_interval(for example 20–30 s),keep_alive_timeout(10 s) andkeep_alive_while_idle(true)on the endpoint, exposed throughClientOptionswith those defaults. Confirm the gateway's Kestrel ping-rate limits tolerate the interval. - Test idea: Local TCP proxy between client and a fake server; open a stream, then make the proxy silently drop packets (no close). Assert the stream yields
Error::Unavailable/Transportwithin interval + timeout.
CRS-002 — attach_secrets scrubs only Error::MxAccess
- Severity: Low. Category: Bug. Confidence: Confirmed (code), Plausible (impact).
- Location:
clients/rust/src/session.rs:1215-1224(used at 820, 853, 894);clients/rust/src/error.rs:149-152(CommandErrorderivesDebugover the whole reply),error.rs:171-185(Display printsprotocol_status.message). - Description: For
write_secured,write_secured2andauthenticate_user, the error is passed throughattach_secrets, which rewrites only theError::MxAccessarm and returns every other variant untouched. A reply whose protocol status is anything other thanOK/MXACCESS_FAILUREbecomesError::Command(CommandError), whose Display printsprotocol_status.messageand whose derivedDebugprintsdiagnostic_messageand everystatuses[].diagnostic_textverbatim. The Java (invokeCommandRedacted,MxGatewaySession.java:1140-1162) and Python (_redact_error,session.py:979-1001) clients scrub every error type;Error::redact_secretsinerror.rs:322-376already does the right thing for most variants but is not used here and itself has noCommandarm. - Failure scenario:
authenticate_userfails with a worker/protocol-level status (for exampleWORKER_UNAVAILABLEorINVALID_REQUEST) whose message or diagnostic echoes the supplied credential. The caller logs{error}or{error:?}and the verifier password lands in the log. - Suggested fix: Add a
Commandarm (scrub the reply withscrub_reply_strings) to bothattach_secretsandError::redact_secrets, and route the other variants throughredact_secrets. - Test idea: Fake gateway returns
PROTOCOL_STATUS_CODE_INVALID_REQUESTwith the password inprotocol_status.messageanddiagnostic_message; assert neitherto_string()norformat!("{:?}")contains it.
CRS-003 — Raw tonic::Status retained and printed unredacted
- Severity: Low. Category: Bug. Confidence: Plausible (requires the server or an intermediary to echo a credential).
- Location:
clients/rust/src/error.rs:379-405(mapping),error.rs:91-92(Statusvariant),error.rs:510-522(redact_credentials). - Description:
From<tonic::Status>redacts only the copiedmessagestring. The original status is stored instatus: Box<tonic::Status>and exposed through derivedDebugandsource(), both of which print the unredacted message and metadata. The catch-all arm (_ => Self::Status(Box::new(status))) does not redact at all, and its Display isgateway status error: {0}.redact_credentialsalso only matches whitespace-delimited tokens that start withmxgw_, so"mxgw_…",key=mxgw_…or(mxgw_…)pass through. - Failure scenario: A proxy or gateway error path returns
INTERNAL/INVALID_ARGUMENTwith the authorization value in the description;eprintln!("{error}")(asmxgw-climain.rs:42does) prints the key. - Suggested fix: Rebuild the stored status with the redacted message (as
redact_secrets::scrub_statusalready does) in every arm including the catch-all, and make the redactor substring-based on themxgw_[A-Za-z0-9_-]+shape. - Test idea:
Error::from(Status::internal("bad header \"mxgw_id_secret\"")); assert Display and Debug contain nosecret.
CRS-004 — CLI batch mode dials a new channel per line
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location:
clients/rust/crates/mxgw-cli/src/batch.rs:49-64,clients/rust/crates/mxgw-cli/src/connect.rs:7-21. The Java CLI has the same shape (MxGatewayCli.java:2066-2067, every commandtry (… clientFactory.connect(…))); Python is CPY-005. - Description: Batch mode exists to avoid per-command process start-up, but each dispatched line calls
GatewayClient::connect, which builds a freshChannel(TCP + optional TLS handshake + HTTP/2 settings, plus a CA-file read) and drops it at the end of the command. - Failure scenario: The e2e matrix or a scripted run issues hundreds of commands; each pays connection set-up, dominating latency for small commands and churning gateway connections.
- Suggested fix: Cache one
GatewayClient/GalaxyClientper distinctConnectionArgsfor the lifetime ofrun_batchand pass it intodispatch. - Test idea: Count accepted connections on a fake server across N batch lines; expect 1.
Java
CJV-001 — close() only calls shutdown(); open streams and blocked readers survive
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location:
clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClient.java:369-374,GalaxyRepositoryClient.java:374-379; reader sideMxEventStream.java:149-162,DeployEventStream.java:105-115. - Description:
close()(theAutoCloseablepath used by try-with-resources) callsownedChannel.shutdown()and returns.ManagedChannel.shutdown()rejects new calls but lets existing calls run to completion. AStreamEvents/StreamAlarms/WatchDeployEventscall has no deadline by default (streamTimeoutnull), so it never completes; the channel never terminates, its Netty threads stay alive, the gateway keeps a subscriber slot, and any thread blocked inMxEventStream.hasNext()(queue.take()) stays blocked. OnlycloseAndAwaitTermination()escalates toshutdownNow(). - Failure scenario: Application shuts down with
try (MxGatewayClient client = …)while a worker thread iteratessession.streamEvents().close()returns immediately, the reader thread never wakes, and an executorawaitTerminationon that thread times out. In default single-subscriber mode the still-open stream also occupies the session's only subscriber slot. - Suggested fix: Track open stream handles in the client and cancel them in
close(), or haveclose()callshutdownNow()after a shortawaitTermination. Document the difference ifshutdown()semantics are kept. - Test idea: In-process server with a never-completing stream; start a reader thread on
hasNext(), callclient.close(), assert the reader returns/throws within a bound andchannel.isTerminated()becomes true.
CJV-002 — GalaxyRepositoryClient ignores the lenient-TLS default
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location:
GalaxyRepositoryClient.java:413-425versusMxGatewayClient.java:400-421; contract atMxGatewayClientOptions.java:107-115. - Description:
MxGatewayClient.createChannelhas four branches: plaintext, pinned CA, lenient (!requireCertificateValidation()→InsecureTrustManagerFactory), strict.GalaxyRepositoryClient.createChannelhas only plaintext, pinned CA anduseTransportSecurity(). With TLS, no CA file and the defaultrequireCertificateValidation=false, the options contract says the gateway's self-signed certificate is accepted; the Galaxy client instead validates against the JVM trust store. - Failure scenario: A deployment with a self-signed gateway certificate:
MxGatewayClient.connect(options)works,GalaxyRepositoryClient.connect(options)with the same options fails every RPC withUNAVAILABLE(handshake failure). The Java CLIgalaxy-*commands fail where the session commands succeed. - Suggested fix: Move channel construction into one shared helper used by both clients.
- Test idea: Extend
MxGatewayClientTlsTeststo run the lenient-default case againstGalaxyRepositoryClientwith a self-signed in-process server.
CJV-003 — No keepalive on the Netty channel
- Severity: Medium. Category: Bug. Confidence: Plausible.
- Location:
MxGatewayClient.java:392-426,GalaxyRepositoryClient.java:405-430. - Description:
NettyChannelBuilderis built withoutkeepAliveTime/keepAliveTimeout/keepAliveWithoutCalls; grpc-java's default disables keepalive. Combined with deadline-less streams this is the same half-open hang as CRS-001:MxEventStream.hasNext()blocks inqueue.take()indefinitely and async observers never receiveonError. - Failure scenario: As CRS-001, for an Ignition module or service holding
streamEvents()across a firewall idle timeout. - Suggested fix:
builder.keepAliveTime(30, SECONDS).keepAliveTimeout(10, SECONDS)with options to tune, coordinated with the server's ping policy. - Test idea: As CRS-001 with a black-holing proxy; assert
hasNext()throws within the keepalive bound.
CJV-004 — Iterator streams rethrow raw StatusRuntimeException
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
MxEventStream.java:77-83and100-103;DeployEventStream.java:50-56and73-76. Mapping that is skipped:MxGatewayErrors.java:13-29. - Description:
onErrorenqueues the gRPCThrowableas-is andhasNext()rethrows anyRuntimeExceptionunchanged. Every unary path maps throughMxGatewayErrors.fromGrpc(typedMxGatewayAuthenticationException/MxGatewayAuthorizationException, credential redaction of the description); the two iterator streams do not. Only non-runtime throwables are wrapped inMxGatewayException. - Failure scenario: An
events:readkey attaches to a session owned by another key. The gateway returnsPERMISSION_DENIED; the caller'scatch (MxGatewayAuthorizationException | MxGatewayException e)around the loop does not match and a rawio.grpc.StatusRuntimeExceptionescapes, with its description unredacted. The same happens forUNAUTHENTICATEDandUNAVAILABLE, so reconnect logic keyed onMxGatewayExceptionnever fires. - Suggested fix: In
hasNext(), passStatusRuntimeExceptionthroughMxGatewayErrors.fromGrpc("stream events", …)(keep the interrupt case distinguishable).MxEventStreamTestsline 44 pins the raw type for the interrupt path and needs updating. - Test idea: Feed
observer().onError(Status.PERMISSION_DENIED.asRuntimeException()); asserthasNext()throwsMxGatewayAuthorizationException.
CJV-005 — DeployEventStream.take() does not cancel the RPC on interrupt
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
DeployEventStream.java:105-115(compareMxEventStream.java:149-162, which cancels). - Description: On
InterruptedExceptionthe method restores the interrupt flag and returns a syntheticCANCELLEDexception, but never callsrequestStream.cancel(…).hasNext()then marks the iterator ended. The underlyingWatchDeployEventscall stays open until its 16-slot queue overflows; deploy events are rare, so in practice it stays open until the channel is torn down (and see CJV-001 for whyclose()does not do that). - Failure scenario: A watcher thread is interrupted during shutdown or task cancellation and abandons the iterator without calling
close(); the server-side watch subscription leaks for the life of the channel. - Suggested fix: Cancel the request stream in the interrupt branch, as
MxEventStreamdoes. - Test idea: Mirror
interruptCancelsCallAndRestoresInterruptFlagforDeployEventStreamand assertcancelCount == 1.
CJV-006 — Typed helpers return 0 / empty list on a reply without the payload
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
MxGatewaySession.java:149-155(register),192-198(addItem),226-232(addItem2),354,374and the other bulk helpers (reply.getXxxBulk().getResultsList()),574-595(readBulk), drain at1097-1104. - Description: When the reply carries neither the typed payload nor an int32
return_value, protobuf default accessors yield0or an empty list and the helper returns it as a valid result.MxGatewayMalformedReplyExceptionexists and the Rust client raisesMalformedReplyin the same positions (session.rs:1110-1197,1287-1343). - Failure scenario: A contract mismatch (older/newer gateway, wrong reply arm) makes
registerreturn handle0; every followingaddItem(0, …)fails with an unrelated invalid-handle MXAccess error.subscribeBulkreturning an empty list reads as "nothing subscribed, no failures". - Suggested fix: Check
hasXxx()/getReturnValue().getKindCase()and throwMxGatewayMalformedReplyExceptionotherwise. - Test idea: Fake stub returns an OK
MxCommandReplywith no payload; assert each helper throws.
CJV-007 — SecureRandom for every command correlation id
- Severity: Low. Category: Performance. Confidence: Plausible (not measured).
- Location:
MxGatewaySession.java:77,1114-1120,1278-1282. - Description: Every
invokeCommanddraws 16 bytes from a shared staticSecureRandomand hex-formats them. Correlation ids are diagnostic, not security tokens.SecureRandom.nextBytesis serialized internally, so concurrent callers on one JVM contend on it, and on some platforms it reads from the kernel. - Failure scenario: A multi-threaded poller issuing high-rate
readBulk/writecalls sees lock contention inSecureRandomin profiles. - Suggested fix: Use a per-process random prefix plus an
AtomicLongcounter (as the Rust client does), orThreadLocalRandom. - Test idea: JMH microbenchmark of
newCorrelationId()at 1 and 16 threads before/after.
Python
CPY-001 — Enum .Name() raises ValueError on unknown values while building typed errors
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location:
clients/python/src/zb_mom_ww_mxgateway/errors.py:95(pb.ProtocolStatusCode.Name(code)),errors.py:169(pb.MxStatusCategory.Name(status.category)). - Description: proto3 enums are open, so a gateway newer than the client's generated code can send a numeric value the client has no name for.
EnumTypeWrapper.NameraisesValueErrorfor such values. Line 169 runs for every status entry whenever anMxAccessErrormessage is built; line 95 runs when the protocol status message is empty. In both cases theValueErrorreplaces the typed gateway error. The Rust client (try_from(...).unwrap_or(Unspecified)) and Java (UNRECOGNIZED) tolerate this. - Failure scenario: A gateway adds
MX_STATUS_CATEGORY_*value 11 (or a newProtocolStatusCode). A failing write on an older Python client raisesValueError: Enum MxStatusCategory has no name defined for value 11instead ofMxAccessError;except MxGatewayErrorhandlers and the CLI's_runwrapper do not catch it, and the secured-write redaction path (_invoke_redactedcatches onlyMxGatewayError) is bypassed. - Suggested fix: Use a small helper that falls back to
str(value)onValueError. - Test idea: Build an
MxCommandReplywithstatuses[0].category = 99; assertensure_mxaccess_successraisesMxAccessError. Same forensure_protocol_successwith code 999 and an empty message.
CPY-002 — No keepalive channel options
- Severity: Medium. Category: Bug. Confidence: Plausible.
- Location:
clients/python/src/zb_mom_ww_mxgateway/options.py:189-205; streams atclient.py:141-145,183-187,205-209,galaxy.py:260-271; defaultstream_timeout=Noneatoptions.py:31. - Description:
channel_optionscontains only the two message-size limits and the optional target-name override. gRPC core keepalive is disabled by default for clients, and streams have no deadline unlessstream_timeoutis set. Same half-open hang as CRS-001:async for item in session.stream_events()never yields and never raises. - Failure scenario: As CRS-001.
- Suggested fix: Add
grpc.keepalive_time_ms,grpc.keepalive_timeout_ms,grpc.keepalive_permit_without_callsandgrpc.http2.max_pings_without_data=0with sensible defaults, tunable viaClientOptions. - Test idea: As CRS-001 with a black-holing proxy; assert the iterator raises
MxGatewayTransportErrorwithin the keepalive bound.
CPY-003 — map_rpc_error drops the status code and does not redact credentials
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/python/src/zb_mom_ww_mxgateway/errors.py:60-72. - Description: Only
UNAUTHENTICATEDandPERMISSION_DENIEDget distinct types.DEADLINE_EXCEEDED,UNAVAILABLE,RESOURCE_EXHAUSTEDandCANCELLEDall become a bareMxGatewayTransportErrorwith nocodeattribute, so a caller implementing reconnect/backoff must reach into__cause__.code(). The Rust client hasTimeout/Cancelled/Unavailable. Separately,detailsis interpolated verbatim; Rust and Java pass it through amxgw_/Bearerredactor, Python relies on each caller (the CLI does exact-match redaction in_run, library users get none). - Failure scenario: A reconnect loop cannot tell "gateway unavailable, retry with backoff" from "deadline exceeded on a non-idempotent write, do not blindly retry" without inspecting the chained gRPC exception; code that only uses the public hierarchy retries both or neither.
- Suggested fix: Store
codeonMxGatewayTransportError(and/or addMxGatewayTimeoutError,MxGatewayUnavailableErrorsubclasses), and rundetailsthrough a credential redactor. - Test idea: Map fake
RpcErrors for each code; assert distinct type or.code, and that a details string containingBearer mxgw_x_yis redacted.
CPY-004 — register / add_item / add_item2 return 0 on a reply without the payload
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location:
clients/python/src/zb_mom_ww_mxgateway/session.py:97,146, and theadd_item2return that follows157-168; contrast withsession.py:724-726,752-754,782-784, which raiseMalformedReplyError. - Description: These helpers read
reply.register.server_handle/reply.add_item.item_handlewithoutHasFieldor areturn_valuefallback, so a reply missing the payload silently yields handle0. The same module already raisesMalformedReplyErrorforauthenticate_user,archestra_user_to_idandadd_buffered_item, and the Rust client does so for all of them. - Failure scenario: As CJV-006: handle
0flows into later calls and surfaces as an unrelated MXAccess invalid-handle failure. - Suggested fix: Apply the existing
HasField/ int32return_value/MalformedReplyErrorpattern to these three helpers (and the bulk helpers). - Test idea: Fake stub returns an OK reply with no payload; assert
MalformedReplyError.
CPY-005 — CLI batch mode: new event loop, channel and TOFU probe per line
- Severity: Low. Category: Performance. Confidence: Confirmed.
- Location:
clients/python/src/zb_mom_ww_mxgateway_cli/commands.py:78-99,102-126,1460-1473,1529-1549; probe atzb_mom_ww_mxgateway/options.py:153-158. - Description: Each batch line re-enters Click, which calls
asyncio.run(new loop),GatewayClient.connect(newgrpc.aiochannel) and, on the default lenient-TLS path,ssl.get_server_certificate— a separate blocking TCP+TLS handshake in a worker thread before the real channel handshake. So a TLS batch line costs two TLS handshakes plus loop and channel set-up and teardown. - Failure scenario: Matrix or scripted batch runs against a TLS gateway spend most of their time in connection set-up; the gateway sees two short-lived connections per command.
- Suggested fix: Run the batch loop inside one event loop and reuse a client per distinct connection options; at minimum cache the resolved
ChannelSecurityper endpoint for the process. - Test idea: Count accepted TLS connections on a test server across N batch lines; expect 1–2 rather than 2N.
CPY-006 — smoke advises before attaching the event stream
- Severity: Low. Category: Bug. Confidence: Plausible.
- Location:
clients/python/src/zb_mom_ww_mxgateway_cli/commands.py:1231-1241; server behaviour atsrc/ZB.MOM.WW.MxGateway.Server/Grpc/EventStreamService.cs:81-82(fresh stream: "plain attach, no replay"); contract note atmxaccess_gateway.proto:87-100. - Description:
_smokerunsregister→add_item→adviseand only then openssession.stream_events()withafter_worker_sequence=0. A fresh stream does not replay the ring, and the proto documents exactly this attach race as the reasonemit_stream_attachedexists. The initialOnDataChangefor the advised item can be published before the subscriber registers. - Failure scenario: Against a static tag the only event is the initial value; it is published before the stream attaches,
_collect_eventswaits out--timeoutand the smoke returns an emptyeventslist, an intermittent failure in the cross-language matrix. - Suggested fix: Open the stream before
advise(requestemit_stream_attached=Truewhen the gateway advertisesstream-events-attached-ackand wait for the sentinel), or attach withafter_worker_sequenceset so the ring is replayed. - Test idea: Fake gateway that emits the initial event synchronously inside
Adviseand drops events with no subscriber; assert smoke still collects it.