Files
mxaccessgw/code-reviews/2026-12-02-perf-bugs/clients-rust-java-python.md
T

196 lines
25 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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: None` default).
- Description: The `Endpoint` is configured with `connect_timeout` and TLS only. No `http2_keep_alive_interval`, `keep_alive_timeout`, `keep_alive_while_idle` or `tcp_keepalive` is set, and streaming RPCs carry no deadline unless the caller opts into `with_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().await` never resolves and never errors, so the consumer never reaches its reconnect/`events_after` path. 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 by `call_timeout`; streams are not.
- Suggested fix: Set `http2_keep_alive_interval` (for example 20–30 s), `keep_alive_timeout` (10 s) and `keep_alive_while_idle(true)` on the endpoint, exposed through `ClientOptions` with 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`/`Transport` within 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` (`CommandError` derives `Debug` over the whole reply), `error.rs:171-185` (Display prints `protocol_status.message`).
- Description: For `write_secured`, `write_secured2` and `authenticate_user`, the error is passed through `attach_secrets`, which rewrites only the `Error::MxAccess` arm and returns every other variant untouched. A reply whose protocol status is anything other than `OK`/`MXACCESS_FAILURE` becomes `Error::Command(CommandError)`, whose Display prints `protocol_status.message` and whose derived `Debug` prints `diagnostic_message` and every `statuses[].diagnostic_text` verbatim. The Java (`invokeCommandRedacted`, `MxGatewaySession.java:1140-1162`) and Python (`_redact_error`, `session.py:979-1001`) clients scrub every error type; `Error::redact_secrets` in `error.rs:322-376` already does the right thing for most variants but is not used here and itself has no `Command` arm.
- Failure scenario: `authenticate_user` fails with a worker/protocol-level status (for example `WORKER_UNAVAILABLE` or `INVALID_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 `Command` arm (scrub the reply with `scrub_reply_strings`) to both `attach_secrets` and `Error::redact_secrets`, and route the other variants through `redact_secrets`.
- Test idea: Fake gateway returns `PROTOCOL_STATUS_CODE_INVALID_REQUEST` with the password in `protocol_status.message` and `diagnostic_message`; assert neither `to_string()` nor `format!("{:?}")` 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` (`Status` variant), `error.rs:510-522` (`redact_credentials`).
- Description: `From<tonic::Status>` redacts only the copied `message` string. The original status is stored in `status: Box<tonic::Status>` and exposed through derived `Debug` and `source()`, 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 is `gateway status error: {0}`. `redact_credentials` also only matches whitespace-delimited tokens that *start* with `mxgw_`, so `"mxgw_…"`, `key=mxgw_…` or `(mxgw_…)` pass through.
- Failure scenario: A proxy or gateway error path returns `INTERNAL`/`INVALID_ARGUMENT` with the authorization value in the description; `eprintln!("{error}")` (as `mxgw-cli` `main.rs:42` does) prints the key.
- Suggested fix: Rebuild the stored status with the redacted message (as `redact_secrets::scrub_status` already does) in every arm including the catch-all, and make the redactor substring-based on the `mxgw_[A-Za-z0-9_-]+` shape.
- Test idea: `Error::from(Status::internal("bad header \"mxgw_id_secret\""))`; assert Display and Debug contain no `secret`.
### 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 command `try (… 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 fresh `Channel` (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`/`GalaxyClient` per distinct `ConnectionArgs` for the lifetime of `run_batch` and pass it into `dispatch`.
- 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 side `MxEventStream.java:149-162`, `DeployEventStream.java:105-115`.
- Description: `close()` (the `AutoCloseable` path used by try-with-resources) calls `ownedChannel.shutdown()` and returns. `ManagedChannel.shutdown()` rejects new calls but lets existing calls run to completion. A `StreamEvents`/`StreamAlarms`/`WatchDeployEvents` call has no deadline by default (`streamTimeout` null), so it never completes; the channel never terminates, its Netty threads stay alive, the gateway keeps a subscriber slot, and any thread blocked in `MxEventStream.hasNext()` (`queue.take()`) stays blocked. Only `closeAndAwaitTermination()` escalates to `shutdownNow()`.
- Failure scenario: Application shuts down with `try (MxGatewayClient client = …)` while a worker thread iterates `session.streamEvents()`. `close()` returns immediately, the reader thread never wakes, and an executor `awaitTermination` on 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 have `close()` call `shutdownNow()` after a short `awaitTermination`. Document the difference if `shutdown()` semantics are kept.
- Test idea: In-process server with a never-completing stream; start a reader thread on `hasNext()`, call `client.close()`, assert the reader returns/throws within a bound and `channel.isTerminated()` becomes true.
### CJV-002 — `GalaxyRepositoryClient` ignores the lenient-TLS default
- Severity: Medium. Category: Bug. Confidence: Confirmed.
- Location: `GalaxyRepositoryClient.java:413-425` versus `MxGatewayClient.java:400-421`; contract at `MxGatewayClientOptions.java:107-115`.
- Description: `MxGatewayClient.createChannel` has four branches: plaintext, pinned CA, lenient (`!requireCertificateValidation()` → `InsecureTrustManagerFactory`), strict. `GalaxyRepositoryClient.createChannel` has only plaintext, pinned CA and `useTransportSecurity()`. With TLS, no CA file and the default `requireCertificateValidation=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 with `UNAVAILABLE` (handshake failure). The Java CLI `galaxy-*` commands fail where the session commands succeed.
- Suggested fix: Move channel construction into one shared helper used by both clients.
- Test idea: Extend `MxGatewayClientTlsTests` to run the lenient-default case against `GalaxyRepositoryClient` with 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: `NettyChannelBuilder` is built without `keepAliveTime` / `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 in `queue.take()` indefinitely and async observers never receive `onError`.
- 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-83` and `100-103`; `DeployEventStream.java:50-56` and `73-76`. Mapping that is skipped: `MxGatewayErrors.java:13-29`.
- Description: `onError` enqueues the gRPC `Throwable` as-is and `hasNext()` rethrows any `RuntimeException` unchanged. Every unary path maps through `MxGatewayErrors.fromGrpc` (typed `MxGatewayAuthenticationException` / `MxGatewayAuthorizationException`, credential redaction of the description); the two iterator streams do not. Only non-runtime throwables are wrapped in `MxGatewayException`.
- Failure scenario: An `events:read` key attaches to a session owned by another key. The gateway returns `PERMISSION_DENIED`; the caller's `catch (MxGatewayAuthorizationException | MxGatewayException e)` around the loop does not match and a raw `io.grpc.StatusRuntimeException` escapes, with its description unredacted. The same happens for `UNAUTHENTICATED` and `UNAVAILABLE`, so reconnect logic keyed on `MxGatewayException` never fires.
- Suggested fix: In `hasNext()`, pass `StatusRuntimeException` through `MxGatewayErrors.fromGrpc("stream events", …)` (keep the interrupt case distinguishable). `MxEventStreamTests` line 44 pins the raw type for the interrupt path and needs updating.
- Test idea: Feed `observer().onError(Status.PERMISSION_DENIED.asRuntimeException())`; assert `hasNext()` throws `MxGatewayAuthorizationException`.
### CJV-005 — `DeployEventStream.take()` does not cancel the RPC on interrupt
- Severity: Low. Category: Bug. Confidence: Confirmed.
- Location: `DeployEventStream.java:105-115` (compare `MxEventStream.java:149-162`, which cancels).
- Description: On `InterruptedException` the method restores the interrupt flag and returns a synthetic `CANCELLED` exception, but never calls `requestStream.cancel(…)`. `hasNext()` then marks the iterator ended. The underlying `WatchDeployEvents` call 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 why `close()` 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 `MxEventStream` does.
- Test idea: Mirror `interruptCancelsCallAndRestoresInterruptFlag` for `DeployEventStream` and assert `cancelCount == 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`, `374` and the other bulk helpers (`reply.getXxxBulk().getResultsList()`), `574-595` (`readBulk`), drain at `1097-1104`.
- Description: When the reply carries neither the typed payload nor an int32 `return_value`, protobuf default accessors yield `0` or an empty list and the helper returns it as a valid result. `MxGatewayMalformedReplyException` exists and the Rust client raises `MalformedReply` in the same positions (`session.rs:1110-1197`, `1287-1343`).
- Failure scenario: A contract mismatch (older/newer gateway, wrong reply arm) makes `register` return handle `0`; every following `addItem(0, …)` fails with an unrelated invalid-handle MXAccess error. `subscribeBulk` returning an empty list reads as "nothing subscribed, no failures".
- Suggested fix: Check `hasXxx()` / `getReturnValue().getKindCase()` and throw `MxGatewayMalformedReplyException` otherwise.
- Test idea: Fake stub returns an OK `MxCommandReply` with 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 `invokeCommand` draws 16 bytes from a shared static `SecureRandom` and hex-formats them. Correlation ids are diagnostic, not security tokens. `SecureRandom.nextBytes` is 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`/`write` calls sees lock contention in `SecureRandom` in profiles.
- Suggested fix: Use a per-process random prefix plus an `AtomicLong` counter (as the Rust client does), or `ThreadLocalRandom`.
- 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.Name` raises `ValueError` for such values. Line 169 runs for every status entry whenever an `MxAccessError` message is built; line 95 runs when the protocol status message is empty. In both cases the `ValueError` replaces 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 new `ProtocolStatusCode`). A failing write on an older Python client raises `ValueError: Enum MxStatusCategory has no name defined for value 11` instead of `MxAccessError`; `except MxGatewayError` handlers and the CLI's `_run` wrapper do not catch it, and the secured-write redaction path (`_invoke_redacted` catches only `MxGatewayError`) is bypassed.
- Suggested fix: Use a small helper that falls back to `str(value)` on `ValueError`.
- Test idea: Build an `MxCommandReply` with `statuses[0].category = 99`; assert `ensure_mxaccess_success` raises `MxAccessError`. Same for `ensure_protocol_success` with 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 at `client.py:141-145`, `183-187`, `205-209`, `galaxy.py:260-271`; default `stream_timeout=None` at `options.py:31`.
- Description: `channel_options` contains 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 unless `stream_timeout` is 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_calls` and `grpc.http2.max_pings_without_data=0` with sensible defaults, tunable via `ClientOptions`.
- Test idea: As CRS-001 with a black-holing proxy; assert the iterator raises `MxGatewayTransportError` within 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 `UNAUTHENTICATED` and `PERMISSION_DENIED` get distinct types. `DEADLINE_EXCEEDED`, `UNAVAILABLE`, `RESOURCE_EXHAUSTED` and `CANCELLED` all become a bare `MxGatewayTransportError` with no `code` attribute, so a caller implementing reconnect/backoff must reach into `__cause__.code()`. The Rust client has `Timeout` / `Cancelled` / `Unavailable`. Separately, `details` is interpolated verbatim; Rust and Java pass it through a `mxgw_`/`Bearer` redactor, 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 `code` on `MxGatewayTransportError` (and/or add `MxGatewayTimeoutError`, `MxGatewayUnavailableError` subclasses), and run `details` through a credential redactor.
- Test idea: Map fake `RpcError`s for each code; assert distinct type or `.code`, and that a details string containing `Bearer mxgw_x_y` is 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 the `add_item2` return that follows `157-168`; contrast with `session.py:724-726`, `752-754`, `782-784`, which raise `MalformedReplyError`.
- Description: These helpers read `reply.register.server_handle` / `reply.add_item.item_handle` without `HasField` or a `return_value` fallback, so a reply missing the payload silently yields handle `0`. The same module already raises `MalformedReplyError` for `authenticate_user`, `archestra_user_to_id` and `add_buffered_item`, and the Rust client does so for all of them.
- Failure scenario: As CJV-006: handle `0` flows into later calls and surfaces as an unrelated MXAccess invalid-handle failure.
- Suggested fix: Apply the existing `HasField` / int32 `return_value` / `MalformedReplyError` pattern 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 at `zb_mom_ww_mxgateway/options.py:153-158`.
- Description: Each batch line re-enters Click, which calls `asyncio.run` (new loop), `GatewayClient.connect` (new `grpc.aio` channel) 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 `ChannelSecurity` per 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 at `src/ZB.MOM.WW.MxGateway.Server/Grpc/EventStreamService.cs:81-82` (fresh stream: "plain attach, no replay"); contract note at `mxaccess_gateway.proto:87-100`.
- Description: `_smoke` runs `register` → `add_item` → `advise` and only then opens `session.stream_events()` with `after_worker_sequence=0`. A fresh stream does not replay the ring, and the proto documents exactly this attach race as the reason `emit_stream_attached` exists. The initial `OnDataChange` for 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_events` waits out `--timeout` and the smoke returns an empty `events` list, an intermittent failure in the cross-language matrix.
- Suggested fix: Open the stream before `advise` (request `emit_stream_attached=True` when the gateway advertises `stream-events-attached-ack` and wait for the sentinel), or attach with `after_worker_sequence` set so the ring is replayed.
- Test idea: Fake gateway that emits the initial event synchronously inside `Advise` and drops events with no subscriber; assert smoke still collects it.