4 Commits

Author SHA1 Message Date
Joseph Doherty e51377c933 code-reviews: regenerate index after resolving all 2026-06-18 findings (0 pending) 2026-06-18 10:58:43 -04:00
Joseph Doherty 2671639250 fix(gateway): resolve 2026-06-18 array-write review findings
- Server-057: extend []-suffix normalization to AddItemBulk/AddBufferedItem so bulk-added
  array tags bind write-capable handles (authz check, worker bind, and registration kept
  consistent); update gateway.md + client READMEs. Tests: AddItemBulk/AddBufferedItem wiring.
- Server-058: assert []-fallback-resolved bare array names are still denied when out of
  read/write scope and that MaxWriteClassification is enforced on suffixed array registrations.
- Contracts-023/024/025: round-trip + field-19 descriptor pin for MxSparseArray; document
  MxSparseArray in docs/Contracts.md; enumerate it in the protocol-version-3 test summary.
- Tests-040: add wiring tests for the six uncovered sparse-write arms (WriteSecured, Write2,
  WriteSecured2, Write2Bulk, WriteSecuredBulk, WriteSecured2Bulk).

dotnet build + targeted tests green (184 passed).
2026-06-18 10:58:42 -04:00
Joseph Doherty 6c853b43af fix(clients): resolve 2026-06-18 array-write review findings
- Client.Dotnet-030: add advise-supervisory to IsKnownGatewayCommand (was dead/unreachable, exit 2)
- Client.Go-035/036/037: usage+README list advise-supervisory; add session-id guard test; fix write2 README wording
- Client.Python-037/038: drop regressed 'scaffold' from pyproject; add advise-supervisory CLI tests
- Client.Rust-039/040: document write_array_elements/advise-supervisory in design doc; pin outer MxValue data_type==0
- Client.Java-049/050/051: sync CLIENT_VERSION to 0.1.2; add advise-supervisory test; guard negative uint32 inputs (pending windev gradle verification)

Client READMEs also updated for Server-057 add-family normalization wording.
.NET/Go/Python/Rust verified green locally; Java pending windev.
2026-06-18 10:58:33 -04:00
Joseph Doherty 85ef453d0d code-reviews: 2026-06-18 re-review of array-write-ergonomics feature at 88915c3
Re-reviewed the 10 modules touched by the MxSparseArray / array-write
ergonomics work (8df5ab3..88915c3). 16 new findings:

- Server-057 (Medium): [] AddItem normalization skips AddItemBulk/AddBufferedItem
- Client.Dotnet-030 (Medium): advise-supervisory missing from IsKnownGatewayCommand (dead command)
- 14 Low: MxSparseArray doc/test gaps, advise-supervisory CLI gaps across clients,
  Client.Java-049 / Client.Python-037 version-bump consistency misses

Worker.Tests and IntegrationTests clean. Worker unchanged by the feature, not re-reviewed.
2026-06-18 10:33:47 -04:00
35 changed files with 1672 additions and 75 deletions
+3 -2
View File
@@ -189,8 +189,9 @@ array before forwarding to the worker. Indices not listed in `elements` are
written as the element type's default — this is a **reset**, not a preserve;
current values at those positions are discarded. `totalLength` is required and
must match the declared length of the array attribute. Bare-name array items
(`Area001.Pump001.Speed`) are auto-normalized to the `[]` form at `AddItem`
so the array attribute accepts the write.
(`Area001.Pump001.Speed`) are auto-normalized to the `[]` form across the whole
add family — `AddItem`, `AddItem2`, `AddItemBulk`, and `AddBufferedItem` — so the
array attribute accepts the write.
## CLI Usage
@@ -2028,6 +2028,7 @@ public static class MxGatewayClientCli
or "register"
or "add-item"
or "advise"
or "advise-supervisory"
or "subscribe-bulk"
or "unsubscribe-bulk"
or "read-bulk"
@@ -82,6 +82,53 @@ public sealed class MxGatewayClientCliTests
Assert.Equal(string.Empty, error.ToString());
}
/// <summary>
/// Client.Dotnet-030: <c>advise-supervisory</c> was present in the command
/// dispatch table but absent from <see cref="MxGatewayClientCli"/>'s
/// <c>IsKnownGatewayCommand</c> guard, so the guard intercepted it first and
/// returned exit code 2 "Unknown command" before dispatch could run. This
/// test asserts the command is recognized (exit ≠ 2, stderr contains no
/// "Unknown command") and reaches the dispatch handler (exit 0, reply written
/// to stdout).
/// </summary>
[Fact]
public async Task RunAsync_AdviseSupervisory_IsRecognizedAndReachesDispatch()
{
using var output = new StringWriter();
using var error = new StringWriter();
FakeCliClient fakeClient = new();
fakeClient.InvokeReplies.Enqueue(new MxCommandReply
{
SessionId = "session-fixture",
Kind = MxCommandKind.AdviseSupervisory,
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
});
int exitCode = await MxGatewayClientCli.RunAsync(
[
"advise-supervisory",
"--endpoint",
"http://localhost:5000",
"--api-key",
"test-api-key",
"--session-id",
"session-fixture",
"--server-handle",
"12",
"--item-handle",
"34",
"--json",
],
output,
error,
_ => fakeClient);
Assert.DoesNotContain("Unknown command", error.ToString());
Assert.Equal(0, exitCode);
Assert.Contains("MX_COMMAND_KIND_ADVISE_SUPERVISORY", output.ToString());
Assert.Equal(string.Empty, error.ToString());
}
/// <summary>Verifies that error output redacts sensitive API key values.</summary>
[Fact]
public async Task RunAsync_ErrorOutput_RedactsApiKey()
+7 -5
View File
@@ -133,8 +133,8 @@ _, err := client.Invoke(ctx, &pb.MxCommandRequest{
err = session.Write(ctx, serverHandle, itemHandle, value, userID)
```
The CLI exposes the same command as `advise-supervisory`, and `write` /
`write2` take `--user-id`.
The CLI exposes the same command as `advise-supervisory`, and `write`
takes `-user-id`.
### Array writes replace the whole array
@@ -167,9 +167,10 @@ err = session.WriteArrayElements(
)
```
`AddItem` (and `AddItem2`) now auto-normalize a bare attribute name to the `[]`
array address form expected by MXAccess, so callers do not need to append `[]`
themselves. Both forms are accepted; duplicates are deduplicated by the gateway.
`AddItem`, `AddItem2`, `AddItemBulk`, and `AddBufferedItem` auto-normalize a
bare array attribute name to the `[]` array address form expected by MXAccess,
so callers do not need to append `[]` themselves. Both forms are accepted;
duplicates are deduplicated by the gateway.
## Galaxy Repository browse
@@ -334,6 +335,7 @@ Every subcommand wired into the CLI. All accept the common flags
| `register` | Register a client name on a session (`-session-id`, `-client-name`). |
| `add-item` | Add an item handle (`-session-id`, `-server-handle`, `-item`). |
| `advise` | Advise (subscribe) one item (`-session-id`, `-server-handle`, `-item-handle`). |
| `advise-supervisory` | Advise one item supervisory — required before a user-id-attributed plain `write`. |
| `subscribe-bulk` | Advise many items in one call. |
| `unsubscribe-bulk` | Unadvise many item handles in one call. |
| `read-bulk` | Read snapshots for many item handles in one call. |
+1 -1
View File
@@ -1295,7 +1295,7 @@ type protojsonMessage interface {
}
func writeUsage(writer io.Writer) {
fmt.Fprintln(writer, "usage: mxgw-go <version|open-session|close-session|ping|register|add-item|advise|subscribe-bulk|unsubscribe-bulk|read-bulk|write-bulk|write2-bulk|write-secured-bulk|write-secured2-bulk|bench-read-bulk|write|stream-events|stream-alarms|acknowledge-alarm|smoke|galaxy-test-connection|galaxy-last-deploy|galaxy-discover|galaxy-watch|galaxy-browse|batch>")
fmt.Fprintln(writer, "usage: mxgw-go <version|open-session|close-session|ping|register|add-item|advise|advise-supervisory|subscribe-bulk|unsubscribe-bulk|read-bulk|write-bulk|write2-bulk|write-secured-bulk|write-secured2-bulk|bench-read-bulk|write|stream-events|stream-alarms|acknowledge-alarm|smoke|galaxy-test-connection|galaxy-last-deploy|galaxy-discover|galaxy-watch|galaxy-browse|batch>")
}
// batchEOR is the end-of-result sentinel emitted to stdout after every command
+10
View File
@@ -558,6 +558,16 @@ func TestRunStreamEventsRequiresSessionID(t *testing.T) {
}
}
// TestRunAdviseSupervisoryRequiresSessionID pins the session-id guard so
// advise-supervisory fails fast before dialing when no session id is supplied.
func TestRunAdviseSupervisoryRequiresSessionID(t *testing.T) {
var stdout, stderr bytes.Buffer
err := runWithIO(t.Context(), []string{"advise-supervisory", "-plaintext", "-api-key", "test"}, &stdout, &stderr)
if err == nil || !strings.Contains(err.Error(), "session-id is required") {
t.Fatalf("advise-supervisory without -session-id error = %v", err)
}
}
// TestRunWriteBulkVariantRejectsMismatchedHandlesAndValues pins the len-mismatch
// guard so a write-bulk with unequal item-handles / values counts fails fast
// before any dial.
+4 -3
View File
@@ -144,8 +144,9 @@ array before forwarding to the worker. Indices not listed in the map are
written as the element type's default — this is a **reset**, not a preserve;
current values at those positions are discarded. `totalLength` is required and
must match the declared length of the array attribute. Bare-name array items
(`Area001.Pump001.Speed`) are auto-normalized to the `[]` form at `AddItem` so
the array attribute accepts the write.
(`Area001.Pump001.Speed`) are auto-normalized to the `[]` form across the whole
add family — `AddItem`, `AddItem2`, `AddItemBulk`, and `AddBufferedItem` — so the
array attribute accepts the write.
## Galaxy Repository Browse
@@ -396,7 +397,7 @@ repositories {
}
dependencies {
implementation 'com.zb.mom.ww.mxgateway:zb-mom-ww-mxgateway-client:0.1.1'
implementation 'com.zb.mom.ww.mxgateway:zb-mom-ww-mxgateway-client:0.1.2'
}
````
@@ -56,7 +56,7 @@ final class MxGatewayCliTests {
assertEquals(0, run.exitCode());
assertEquals("", run.errors());
assertTrue(run.output().contains("mxgateway-java 0.1.1"));
assertTrue(run.output().contains("mxgateway-java 0.1.2"));
assertTrue(run.output().contains("gatewayProtocolVersion=3"));
assertTrue(run.output().contains("workerProtocolVersion=1"));
}
@@ -86,7 +86,7 @@ final class MxGatewayCliTests {
CliRun run = execute(new FakeClientFactory(), "version", "--json");
assertEquals(0, run.exitCode());
assertTrue(run.output().contains("\"clientVersion\":\"0.1.1\""));
assertTrue(run.output().contains("\"clientVersion\":\"0.1.2\""));
assertTrue(run.output().contains("\"gatewayProtocolVersion\":3"));
}
@@ -148,6 +148,26 @@ final class MxGatewayCliTests {
assertTrue(run.output().contains("\"itemHandle\":7"));
}
@Test
void adviseSupervisoryCommandCallsAdviseSupervisoryRaw() {
// Client.Java-050: dedicated test for advise-supervisory, using a
// separate adviseSupervisoryCalled flag so it cannot be masked by the
// plain advise path that shares adviseCalled.
FakeClientFactory factory = new FakeClientFactory();
CliRun run = execute(
factory,
"advise-supervisory",
"--session-id", "session-cli",
"--server-handle", "12",
"--item-handle", "34",
"--json");
assertEquals(0, run.exitCode());
assertTrue(factory.client.session.adviseSupervisoryCalled);
assertFalse(factory.client.session.adviseCalled, "plain advise must not be called");
assertTrue(run.output().contains("\"kind\":\"MX_COMMAND_KIND_ADVISE_SUPERVISORY\""));
}
// ---- ping subcommand (D4) ----
@Test
@@ -1235,6 +1255,7 @@ final class MxGatewayCliTests {
private boolean registerCalled;
private boolean addItemCalled;
private boolean adviseCalled;
private boolean adviseSupervisoryCalled;
private MxValue lastWriteValue;
private String lastPingMessage;
private long lastReadBulkTimeoutMs;
@@ -1304,7 +1325,7 @@ final class MxGatewayCliTests {
@Override
public MxCommandReply adviseSupervisoryRaw(int serverHandle, int itemHandle) {
adviseCalled = true;
adviseSupervisoryCalled = true;
return MxCommandReply.newBuilder()
.setKind(MxCommandKind.MX_COMMAND_KIND_ADVISE_SUPERVISORY)
.setProtocolStatus(ok())
@@ -9,7 +9,7 @@ package com.zb.mom.ww.mxgateway.client;
public final class MxGatewayClientVersion {
private static final int GATEWAY_PROTOCOL_VERSION = 3;
private static final int WORKER_PROTOCOL_VERSION = 1;
private static final String CLIENT_VERSION = "0.1.1";
private static final String CLIENT_VERSION = "0.1.2";
private MxGatewayClientVersion() {
}
@@ -623,13 +623,22 @@ public final class MxGatewaySession implements AutoCloseable {
* supplied indices must be within {@code [0, totalLength)}. Elements are iterated in
* ascending index order so the produced command is deterministic.
*
* <p>Because the proto fields {@code MxSparseArray.total_length} and
* {@code MxSparseElement.index} are {@code uint32}, passing a negative Java {@code int}
* would silently sign-extend to a large unsigned value on the wire. This method
* therefore rejects negative {@code totalLength} and negative element indices with
* {@link IllegalArgumentException} rather than allowing a hard-to-diagnose gateway error.
*
* @param serverHandle the {@code ServerHandle} owning the item
* @param itemHandle the {@code ItemHandle} to write
* @param elementDataType the {@link MxDataType} of the array's elements
* @param totalLength the total length of the expanded array
* @param elements the indices to write mapped to their scalar values; unmentioned
* indices are reset to the element type default
* @param totalLength the total length of the expanded array; must be &gt; 0
* @param elements the indices to write mapped to their scalar values; each index must
* be in {@code [0, totalLength)}; unmentioned indices are reset to the element
* type default
* @param userId the MXAccess user id used for security checks
* @throws IllegalArgumentException if {@code totalLength} is not positive, or if any
* element index is negative or &ge; {@code totalLength}
* @throws MxGatewayException on transport or protocol failure
*/
public void writeArrayElements(
@@ -641,6 +650,16 @@ public final class MxGatewaySession implements AutoCloseable {
int userId) {
Objects.requireNonNull(elementDataType, "elementDataType");
Objects.requireNonNull(elements, "elements");
if (totalLength <= 0) {
throw new IllegalArgumentException("totalLength must be > 0, got " + totalLength);
}
for (Map.Entry<Integer, MxValue> entry : elements.entrySet()) {
int idx = entry.getKey();
if (idx < 0 || idx >= totalLength) {
throw new IllegalArgumentException(
"element index " + idx + " is out of range [0, " + totalLength + ")");
}
}
MxSparseArray.Builder sparse = MxSparseArray.newBuilder()
.setElementDataType(elementDataType)
.setTotalLength(totalLength);
@@ -451,6 +451,64 @@ final class MxGatewayClientSessionTests {
}
}
@Test
void writeArrayElementsRejectsNonPositiveTotalLength() throws Exception {
// Client.Java-051: negative/zero totalLength silently sign-extends to a
// large uint32 on the wire; the client must reject it with
// IllegalArgumentException before building the proto message (before any
// network call is issued).
try (InProcessGateway gateway = InProcessGateway.start(
new TestGatewayService() {}, new AtomicReference<>());
MxGatewayClient client = gateway.client("", Duration.ofSeconds(5))) {
MxGatewaySession session = MxGatewaySession.forSessionId(client, "guard-session");
assertThrows(
IllegalArgumentException.class,
() -> session.writeArrayElements(
1, 2, MxDataType.MX_DATA_TYPE_INTEGER, -1, Map.of(), 0),
"negative totalLength must throw");
assertThrows(
IllegalArgumentException.class,
() -> session.writeArrayElements(
1, 2, MxDataType.MX_DATA_TYPE_INTEGER, 0, Map.of(), 0),
"zero totalLength must throw");
}
}
@Test
void writeArrayElementsRejectsOutOfRangeIndex() throws Exception {
// Client.Java-051: a negative index silently sign-extends to a large
// uint32 on the wire; an index >= totalLength exceeds the declared
// array bounds. Both must be caught before the network call.
try (InProcessGateway gateway = InProcessGateway.start(
new TestGatewayService() {}, new AtomicReference<>());
MxGatewayClient client = gateway.client("", Duration.ofSeconds(5))) {
MxGatewaySession session = MxGatewaySession.forSessionId(client, "guard-session");
assertThrows(
IllegalArgumentException.class,
() -> session.writeArrayElements(
1, 2, MxDataType.MX_DATA_TYPE_INTEGER, 5,
Map.of(-1, MxValues.int32Value(7)), 0),
"negative index must throw");
assertThrows(
IllegalArgumentException.class,
() -> session.writeArrayElements(
1, 2, MxDataType.MX_DATA_TYPE_INTEGER, 5,
Map.of(5, MxValues.int32Value(7)), 0),
"index equal to totalLength must throw");
assertThrows(
IllegalArgumentException.class,
() -> session.writeArrayElements(
1, 2, MxDataType.MX_DATA_TYPE_INTEGER, 5,
Map.of(10, MxValues.int32Value(7)), 0),
"index above totalLength must throw");
}
}
private static ProtocolStatus ok() {
return ProtocolStatus.newBuilder()
.setCode(ProtocolStatusCode.PROTOCOL_STATUS_CODE_OK)
+3 -2
View File
@@ -170,8 +170,9 @@ await session.write_array_elements(
```
Bare-name array items (e.g. `Object.ArrayAttr` without an index suffix) added
via `add_item` auto-normalize to `[]` — they refer to the whole array, not a
single element. Writes through such handles must cover the full array or use
via `add_item`, `add_item2`, `add_item_bulk`, or `add_buffered_item`
auto-normalize to `[]` — they refer to the whole array, not a single element.
Writes through such handles must cover the full array or use
`write_array_elements` to supply `total_length` and let the gateway fill
defaults for the rest.
+1 -1
View File
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "zb-mom-ww-mxaccess-gateway-client"
version = "0.1.2"
description = "Async Python client scaffold for MXAccess Gateway."
description = "Async Python client for MXAccess Gateway."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
@@ -0,0 +1,163 @@
"""Regression tests for Client.Python-037 and Client.Python-038.
Client.Python-037: ``pyproject.toml`` description must not contain "scaffold".
Client.Python-038: ``advise-supervisory`` CLI subcommand must have coverage
(registration smoke test + happy-path command-shape test).
Tests are TDD-first — written before the fix and expected to pass once the
source change lands.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from click.testing import CliRunner
from zb_mom_ww_mxgateway import ClientOptions, GatewayClient
from zb_mom_ww_mxgateway.generated import mxaccess_gateway_pb2 as pb
from zb_mom_ww_mxgateway_cli.commands import main
# ---------------------------------------------------------------------------
# Client.Python-037 — pyproject.toml description must not contain "scaffold".
# ---------------------------------------------------------------------------
def test_pyproject_description_does_not_contain_scaffold() -> None:
"""The ``description`` field in ``pyproject.toml`` must not include the
word "scaffold" — a regression of Client.Python-001 that re-entered the
file at the package-rename commit.
"""
pyproject = (
Path(__file__).resolve().parent.parent / "pyproject.toml"
).read_text(encoding="utf-8")
# Find the description line and assert "scaffold" is absent.
for line in pyproject.splitlines():
stripped = line.strip()
if stripped.startswith("description"):
assert "scaffold" not in stripped.lower(), (
f"pyproject.toml description must not contain 'scaffold': {stripped!r}"
)
return
raise AssertionError("pyproject.toml has no 'description' line")
# ---------------------------------------------------------------------------
# Client.Python-038 — advise-supervisory must be registered + have a happy path.
# ---------------------------------------------------------------------------
def test_advise_supervisory_is_registered() -> None:
"""``advise-supervisory`` must be a registered subcommand of ``main``.
A ``--help`` invocation must exit 0 and the help text must include the
required options (--server-handle and --item-handle).
"""
runner = CliRunner()
result = runner.invoke(main, ["advise-supervisory", "--help"])
assert result.exit_code == 0, result.output
assert "--server-handle" in result.output
assert "--item-handle" in result.output
# --------------- fake-stub infrastructure (mirrors test_review_findings_022_to_026) ----
class _FakeUnary:
def __init__(self, replies: list[Any]) -> None:
self.replies = replies
self.requests: list[Any] = []
self.metadata: tuple[tuple[str, str], ...] | None = None
async def __call__(self, request: Any, *, metadata: tuple[tuple[str, str], ...]) -> Any:
self.requests.append(request)
self.metadata = metadata
return self.replies.pop(0)
class _FakeStub:
def __init__(self) -> None:
self.open_session = _FakeUnary(
[
pb.OpenSessionReply(
session_id="session-1",
protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK),
),
],
)
self.invoke = _FakeUnary([])
self.OpenSession = self.open_session
self.Invoke = self.invoke
def set_invoke_replies(self, replies: list[Any]) -> None:
self.invoke.replies = replies
def _install_fake_connect(monkeypatch: Any, stub: _FakeStub) -> None:
"""Patch ``GatewayClient.connect`` so the CLI uses the supplied fake stub."""
real_connect = GatewayClient.connect
@classmethod # type: ignore[misc]
async def _spy_connect(cls: Any, options: ClientOptions, **kwargs: Any) -> GatewayClient:
return await real_connect(options, stub=stub)
monkeypatch.setattr(GatewayClient, "connect", _spy_connect)
def test_cli_advise_supervisory_happy_path(monkeypatch: Any) -> None:
"""``advise-supervisory`` must forward server_handle and item_handle in an
``MX_COMMAND_KIND_ADVISE_SUPERVISORY`` ``MxCommand``.
Pattern mirrors ``test_cli_acknowledge_alarm_happy_path`` in
``test_review_findings_022_to_026.py``.
"""
stub = _FakeStub()
stub.set_invoke_replies(
[
pb.MxCommandReply(
session_id="session-1",
kind=pb.MX_COMMAND_KIND_ADVISE_SUPERVISORY,
protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK),
),
],
)
_install_fake_connect(monkeypatch, stub)
runner = CliRunner()
result = runner.invoke(
main,
[
"advise-supervisory",
"--endpoint",
"localhost:5000",
"--plaintext",
"--session-id",
"session-1",
"--server-handle",
"7",
"--item-handle",
"42",
"--json",
],
)
assert result.exit_code == 0, result.output
payload = json.loads(result.output)
assert payload["ok"] is True
# Verify the MxCommand shape forwarded to the gateway.
assert len(stub.invoke.requests) == 1
cmd = stub.invoke.requests[0].command
assert cmd.kind == pb.MX_COMMAND_KIND_ADVISE_SUPERVISORY
assert cmd.advise_supervisory.server_handle == 7
assert cmd.advise_supervisory.item_handle == 42
+4 -4
View File
@@ -196,10 +196,10 @@ the existing attribute value.
#### Bare-name array AddItem normalisation
`AddItem` for a bare array attribute name (e.g. `Tank01.Temperature`) is
automatically normalised to `Tank01.Temperature[]` by the gateway so the
worker can resolve the full array. You do not need to append `[]` in client
code; the gateway handles it.
Adding a bare array attribute name (e.g. `Tank01.Temperature`) via `AddItem`,
`AddItem2`, `AddItemBulk`, or `AddBufferedItem` is automatically normalised to
`Tank01.Temperature[]` by the gateway so the worker can resolve the full array.
You do not need to append `[]` in client code; the gateway handles it.
## Galaxy Repository browse
+2
View File
@@ -121,6 +121,7 @@ impl Session {
pub async fn read_bulk<S: AsRef<str>>(&self, server_handle: i32, tag_addresses: &[S], timeout_ms: u32) -> Result<Vec<BulkReadResult>, Error>;
pub async fn write(&self, server_handle: i32, item_handle: i32, value: MxValue, user_id: i32) -> Result<(), Error>;
pub async fn write2(&self, server_handle: i32, item_handle: i32, value: MxValue, timestamp_value: MxValue, user_id: i32) -> Result<(), Error>;
pub async fn write_array_elements(&self, server_handle: i32, item_handle: i32, element_data_type: MxDataType, total_length: u32, elements: impl IntoIterator<Item = (u32, MxValue)>, user_id: i32) -> Result<(), Error>;
pub async fn write_bulk(&self, server_handle: i32, entries: Vec<WriteBulkEntry>) -> Result<Vec<BulkWriteResult>, Error>;
pub async fn write2_bulk(&self, server_handle: i32, entries: Vec<Write2BulkEntry>) -> Result<Vec<BulkWriteResult>, Error>;
pub async fn write_secured_bulk(&self, server_handle: i32, entries: Vec<WriteSecuredBulkEntry>) -> Result<Vec<BulkWriteResult>, Error>;
@@ -333,6 +334,7 @@ mxgw close-session --session-id <id>
mxgw register --session-id <id>
mxgw add-item --session-id <id> --server-handle <h> --item <tag>
mxgw advise --session-id <id> --server-handle <h> --item-handle <h>
mxgw advise-supervisory --session-id <id> --server-handle <h> --item-handle <h>
mxgw subscribe-bulk --session-id <id> --server-handle <h> --items <csv>
mxgw unsubscribe-bulk --session-id <id> --server-handle <h> --item-handles <csv>
mxgw read-bulk --session-id <id> --server-handle <h> --items <csv> [--timeout-ms <ms>]
+16 -1
View File
@@ -1212,7 +1212,9 @@ fn sparse_int32_value(
.collect();
MxValue {
data_type: MxDataType::Integer as i32,
// outer data_type must be 0 (Unspecified); the element type lives only
// inside MxSparseArray.element_data_type, matching the
// `..ProtoMxValue::default()` used in Session::write_array_elements.
variant_type: String::new(),
kind: Some(Kind::SparseArrayValue(MxSparseArray {
element_data_type: MxDataType::Integer as i32,
@@ -1227,6 +1229,11 @@ fn sparse_int32_value(
fn write_array_elements_proto_shape_has_sparse_oneof_kind() {
let proto = sparse_int32_value(5, [(0, 10), (3, 30)]);
assert_eq!(
proto.data_type, 0,
"outer MxValue.data_type must be 0 (Unspecified); element type lives in element_data_type"
);
let Kind::SparseArrayValue(ref sparse) = proto.kind.as_ref().unwrap() else {
panic!("expected SparseArrayValue kind, got {:?}", proto.kind);
};
@@ -1253,6 +1260,10 @@ fn write_array_elements_proto_shape_has_sparse_oneof_kind() {
#[test]
fn write_array_elements_empty_elements_is_valid_all_defaults() {
let proto = sparse_int32_value(8, []);
assert_eq!(
proto.data_type, 0,
"outer MxValue.data_type must be 0 (Unspecified) even with no elements"
);
let Kind::SparseArrayValue(ref sparse) = proto.kind.as_ref().unwrap() else {
panic!("expected SparseArrayValue kind");
};
@@ -1269,6 +1280,10 @@ fn sparse_array_value_round_trips_through_client_mx_value_projection_as_unset()
// (e.g. a future version bug), the projection should degrade to Unset
// rather than panic, because the enum variant is not readable.
let proto = sparse_int32_value(4, [(1, 99)]);
assert_eq!(
proto.data_type, 0,
"outer MxValue.data_type must be 0 (Unspecified)"
);
let client_value = ClientMxValue::from_proto(proto);
assert_eq!(
client_value.projection(),
+47 -2
View File
@@ -4,8 +4,8 @@
|---|---|
| Module | `clients/dotnet` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
@@ -604,6 +604,32 @@ Net effect at HEAD: `dotnet build clients/dotnet/ZB.MOM.WW.MxGateway.Client.slnx
**Resolution:** 2026-06-15 — Confirmed against source: `Children => _children` returned the live mutable backing `List<LazyBrowseNode>` and `IsExpanded => _isExpanded` read a plain `bool`, while `ExpandAsync` appended to that same list under `_expandLock` with no release/acquire barrier to lock-free readers — so a concurrent reader could enumerate a mid-append list and throw `InvalidOperationException` ("collection was modified"). Applied option (b) (safe publication): `ExpandAsync` now accumulates children into a method-local `List<LazyBrowseNode>` and, only when fully drained across all pages, publishes it via `Volatile.Write(ref _children, children)` (release) immediately before setting the now-`volatile bool _isExpanded = true`. The `_children` field is an `IReadOnlyList<LazyBrowseNode>` read via `Volatile.Read` from the `Children` getter (acquire), so a reader that observes `IsExpanded == true` always sees the fully-populated snapshot and never enumerates a partially-built list. Updated the `ExpandAsync` `<remarks>` to document the strengthened concurrent-read guarantee. Regression test `LazyBrowseNodeTests.Expand_ConcurrentReadOfChildren_NeverTearsAndPublishesAtomically` gates the child-page RPCs (via a new `FakeGalaxyRepositoryTransport.BrowseChildrenGate` hook) to hold the expand mid-flight while a background reader spins enumerating `Children` and reading `IsExpanded`, asserting no exception escapes and that once `IsExpanded` is true the published snapshot has all five children. Verified red against the pre-fix code (the reader threw `InvalidOperationException: Collection was modified` deterministically across three runs) and green after the fix.
#### 2026-06-18 re-review (commit 88915c3)
Re-review of changes since `8df5ab3`. The diff adds `WriteArrayElementsAsync` /
`BuildSparseArray` to `MxGatewaySession`, an `advise-supervisory` CLI subcommand,
the Client.Dotnet-028 (`TryResolveApiKey`) and Client.Dotnet-029 (`IMxGatewayCliClient`
summary) in-source fixes, two tests covering the new sparse-array helper, a "Write
Semantics And Common Pitfalls" section in README.md, the `LazyBrowseNode` Client.Dotnet-027
rationale comment, and a version bump (`0.1.1` → `0.1.2`). The 029 and 028 fixes are
correctly applied. The `isLongRunning` / `galaxy-browse` fix from Client.Dotnet-026 is
correctly present. One Medium correctness bug found: `advise-supervisory` is in the
dispatch table but missing from `IsKnownGatewayCommand`, making the command
unreachable (exit 2 "Unknown command").
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | Issue found (Client.Dotnet-030): `advise-supervisory` is present in the `command switch` dispatch table but absent from `IsKnownGatewayCommand`; the guard at line 91 intercepts it first and returns exit code 2 "Unknown command", making the command completely non-functional. `WriteArrayElementsAsync` / `BuildSparseArray` logic is correct: `elementDataType` and `totalLength` are threaded through faithfully, `MxValue.SparseArrayValue` is set and the outer `MxValue.DataType` (unused by the expander) is left at the proto3 default — consistent with all other language clients. Index validation (out-of-range, duplicate, zero total_length) is correctly deferred to `SparseArrayExpander` gateway-side, consistent with Go/Rust/Python/Java. |
| 2 | mxaccessgw conventions | No issues found — no forked proto, `authorization: Bearer` metadata unchanged, MXAccess parity preserved (sparse array is a write-only helper, reset-not-preserve semantics documented). `Async` suffix on `WriteArrayElementsAsync` correct. `BuildSparseArray` is `internal static` — appropriate since it is used by both the method and tests. |
| 3 | Concurrency & thread safety | No issues found — `BuildSparseArray` is a pure static factory with no shared state; `WriteArrayElementsAsync` delegates to the existing `WriteAsync`. |
| 4 | Error handling & resilience | No issues found — `ArgumentNullException.ThrowIfNull(elements)` covers the null-dict case; invalid indices / unsupported element types surface as `InvalidArgument` from `SparseArrayExpander`, which the existing `RpcExceptionMapper` maps to `MxGatewayException` with `StatusCode`. |
| 5 | Security | No issues found — `TryResolveApiKey` correctly wired; regression test covers the env-var-sourced key path. |
| 6 | Performance & resource management | No issues found — `BuildSparseArray` is O(n) allocation with no unnecessary copies; the protobuf `repeated` list is built in one pass. |
| 7 | Design-document adherence | No issues found — sparse array semantics match the proto comment on `MxSparseArray` ("reset, NOT preserved") and `SparseArrayExpander`'s design; the README "bare-name auto-normalized to `[]` form at AddItem" claim is confirmed by `GatewaySession.cs:973` and `SessionManager.cs:52`. |
| 8 | Code organization & conventions | No issues found beyond the correctness finding above (missing `IsKnownGatewayCommand` entry is the same defect). |
| 9 | Testing coverage | No issues found — `BuildSparseArray_ProducesSparseArrayValueWithCorrectTotalLengthAndElements` and `WriteArrayElementsAsync_BuildsWriteCommandWithSparseArrayValue` cover the happy path; `RunAsync_ErrorOutput_RedactsApiKey_WhenSourcedFromEnvironmentVariable` covers the Client.Dotnet-028 path. No test for `advise-supervisory` (the new command is dead, so there is nothing to test until the `IsKnownGatewayCommand` gap is fixed). |
| 10 | Documentation & comments | No issues found — the "Write Semantics And Common Pitfalls" README section accurately describes default-fill / reset semantics, the supervisory-advise prerequisite for user attribution, and the auto-`[]` normalization. XML docs on `WriteArrayElementsAsync` and `BuildSparseArray` are accurate and complete; the `<remarks>` block on `WriteArrayElementsAsync` correctly emphasises "RESET, not preserve". |
#### 2026-06-16 re-review (commit 8df5ab3)
Re-review of the .NET client delta: `LazyBrowseNode` lazy paging + tests, the new `MxGatewayClientCli` galaxy-browse surface + tests, `GalaxyClientFactory`/adapter seam. Client.Dotnet-025 (LazyBrowseNode publish ordering) confirmed resolved. One Medium security regression.
@@ -680,3 +706,22 @@ Re-review of the .NET client delta: `LazyBrowseNode` lazy paging + tests, the ne
**Recommendation:** Add a one-line `<summary>` describing the interface and noting `MxGatewayCliClientAdapter` is the production binding.
**Resolution:** 2026-06-16 — Confirmed against source: the interface declaration at `IMxGatewayCliClient.cs:6` had no type-level `<summary>` (only the members were documented). Added a type-level `<summary>` describing the interface as the CLI's transport seam over the gateway and Galaxy Repository RPCs, naming `MxGatewayCliClientAdapter` (over a real `MxGatewayClient`) as the production binding and the in-memory fake as the test substitute. Pure documentation change — no test needed.
### Client.Dotnet-030
| Field | Value |
|---|---|
| Severity | Medium |
| Category | Correctness & logic bugs |
| Location | `clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs:91-93,113,2023-2050` |
| Status | Resolved |
**Description:** `advise-supervisory` was added to the `command switch` dispatch table at line 113 but was not added to `IsKnownGatewayCommand` (the exhaustive list at lines 2023–2050). The guard at line 91 evaluates `IsKnownGatewayCommand(command)` before the dispatch table is reached; because `"advise-supervisory"` is absent from that list, `WriteUnknownCommand` is called and the method returns exit code 2 with "Unknown command 'advise-supervisory'." printed to stderr. The handler at line 113 is dead code — it can never execute.
The README documents `advise-supervisory` (`clients/dotnet/README.md:159` "The CLI exposes the same command as `advise-supervisory`") and `WriteUsage` lists it (line 2093), so callers following the docs will receive a confusing failure with no obvious remedy.
Note: `"advise"` is correctly present in `IsKnownGatewayCommand` (line 2030); the omission of `"advise-supervisory"` is an oversight introduced when the command was added in this diff.
**Recommendation:** Add `or "advise-supervisory"` to the `IsKnownGatewayCommand` expression (e.g. after `"advise"` at line 2030). Add a test (`MxGatewayClientCliTests`) that invokes `advise-supervisory` through `RunAsync` with a fake client and asserts exit code 0 (not 2) and that the reply is written to stdout — this would have caught the regression immediately.
**Resolution:** 2026-06-18 — Confirmed root cause: `"advise-supervisory"` was absent from the `IsKnownGatewayCommand` expression in `MxGatewayClientCli.cs`, so the guard at line 91 intercepted every invocation and returned exit 2 "Unknown command 'advise-supervisory'." before the dispatch table was reached. Added `or "advise-supervisory"` after `or "advise"` at line 2031 in `IsKnownGatewayCommand`. Regression test `MxGatewayClientCliTests.RunAsync_AdviseSupervisory_IsRecognizedAndReachesDispatch` verified red (stderr contained "Unknown command 'advise-supervisory'.") against the pre-fix code and green after; full 86-test suite passes.
+75 -2
View File
@@ -4,8 +4,8 @@
|---|---|
| Module | `clients/go` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
@@ -798,3 +798,76 @@ if ($dirty) {
**Recommendation:** Add a complete subcommand reference, and document the `batch` EOR-sentinel protocol and line cap.
**Resolution:** 2026-06-16 — Expanded the README CLI section with a "Subcommand reference" table covering all 27 subcommands wired into `run` (incl. `ping`, `galaxy-browse`, `read-bulk`, the four bulk-write variants, `bench-read-bulk`, `stream-alarms`, `acknowledge-alarm`, `batch`), refreshed the example block, and added a "`batch` mode" subsection documenting the `__MXGW_BATCH_EOR__` end-of-result sentinel, the JSON error framing, blank-line skipping, and the 16 MiB scanner line cap.
#### 2026-06-18 re-review (commit 88915c3)
Re-review of `clients/go/` changes since `8df5ab3`: `WriteArrayElements` default-fill helper (`mxgateway/session.go`), `MxSparseArray`/`MxSparseElement` type aliases (`types.go`), `advise-supervisory` CLI subcommand (`cmd/mxgw-go/main.go`), prior-finding fixes (`runStreamEvents` signal handler, `closeSmokeSession` double-defer, `runGalaxyWatch` limit-drain, test gaps from Client.Go-033), and README write-semantics documentation. `gofmt -l .`, `go vet ./...`, `go build ./...`, and `go test ./... -count=1` are all clean.
`WriteArrayElements` is structurally correct: `sort.Slice` on unique `uint32` keys produces a deterministic slice (no stable-sort needed); ranging over a nil map produces an empty slice without panic (Go idiom); the `SparseArrayValue` oneof arm is set correctly. Three new findings: `advise-supervisory` missing from `writeUsage` and the README subcommand table; no CLI-level test for `advise-supervisory`; README claims `write2` as a CLI command when Go exposes only `write2-bulk`.
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | No issues found. `buildSparseArrayValue` handles nil map (empty-range, no panic), duplicate-free `uint32` keys, and deterministic sort correctly. |
| 2 | mxaccessgw conventions | No issues found. `gofmt -l .` / `go vet ./...` clean; the direct `pb` import in `runAdviseSupervisory` matches the README-documented escape-hatch pattern. |
| 3 | Concurrency & thread safety | No issues found. `WriteArrayElements` is a pure helper with no shared state. |
| 4 | Error handling & resilience | No issues found. `WriteArrayElements` delegates to `Write`; error propagation is consistent with sibling methods. |
| 5 | Security | No issues found. |
| 6 | Performance & resource management | No issues found. `sort.Slice` on a small caller-sized slice is appropriate. |
| 7 | Design-document adherence | No issues found. `SparseArrayValue` oneof arm matches the proto contract; RESET semantics documented in code and README. |
| 8 | Code organization & conventions | `advise-supervisory` is wired into `run()` but absent from `writeUsage()` and the README subcommand table (Client.Go-035). |
| 9 | Testing coverage | `advise-supervisory` has no CLI-level test, not even the session-id-required guard (Client.Go-036). |
| 10 | Documentation & comments | README "Write Semantics" section claims "`write` / `write2` take `--user-id`" but Go CLI has no standalone `write2` command (Client.Go-037). |
### Client.Go-035
| Field | Value |
|---|---|
| Severity | Low |
| Category | Code organization & conventions |
| Location | `clients/go/cmd/mxgw-go/main.go:1298`, `clients/go/README.md:328-355` |
| Status | Resolved |
**Description:** `advise-supervisory` is wired into the `run()` dispatch switch at `main.go:91-92` but is absent from two surfaces a user consults to discover CLI commands:
1. `writeUsage()` at `main.go:1298` does not list `advise-supervisory` in its pipe-separated command enumeration, so `mxgw-go` invoked with no arguments or an unknown command prints a usage banner that omits the command.
2. The README "Subcommand reference" table at `README.md:328-355` — added in commit `9eedf9d` to be a complete canonical list — also omits `advise-supervisory`.
This is exactly the shape Client.Go-012 (resolved 2026-05-20) and Client.Go-034 (resolved 2026-06-16) documented for previously-missing commands.
**Recommendation:** Add `advise-supervisory` to the `writeUsage` string and to the README subcommand table (e.g., `| advise-supervisory | Advise one item supervisory — required before a userID-attributed plain Write. |`).
**Resolution:** 2026-06-18 — Confirmed both omissions. Added `advise-supervisory` to the pipe-separated command list in `writeUsage()` (after `advise`) and added a row for it in the README "Subcommand reference" table: `| advise-supervisory | Advise one item supervisory — required before a user-id-attributed plain write. |`. `go build ./...` and `go test ./...` green.
### Client.Go-036
| Field | Value |
|---|---|
| Severity | Low |
| Category | Testing coverage |
| Location | `clients/go/cmd/mxgw-go/main_test.go`, `clients/go/cmd/mxgw-go/main.go:364-399` |
| Status | Resolved |
**Description:** `runAdviseSupervisory` has no CLI-level test in `main_test.go`. In particular the session-id-required guard at `main.go:376-378` is untested, unlike every other guard for session-id-required commands (e.g. `TestRunStreamEventsRequiresSessionID`, added in the same commit range by Client.Go-033). A future refactor that removes or conditions the guard has no regression catch. The pattern for adding such a test is already established in the test file and requires no bufconn fake.
**Recommendation:** Add `TestRunAdviseSupervisoryRequiresSessionID` to `cmd/mxgw-go/main_test.go`, driving `runWithIO` with `[]string{"advise-supervisory", "-plaintext", "-api-key", "test"}` (no `-session-id`) and asserting `err.Error()` contains `"session-id is required"`. Mirrors `TestRunStreamEventsRequiresSessionID`.
**Resolution:** 2026-06-18 — Confirmed guard exists at `main.go:376-378` but had no test. Added `TestRunAdviseSupervisoryRequiresSessionID` to `cmd/mxgw-go/main_test.go` (mirrors `TestRunStreamEventsRequiresSessionID`): drives `runWithIO` with `["advise-supervisory", "-plaintext", "-api-key", "test"]` and asserts `err` contains `"session-id is required"`. Test passes immediately (guard was already present); pinned against future removal. `go test ./...` green.
### Client.Go-037
| Field | Value |
|---|---|
| Severity | Low |
| Category | Documentation & comments |
| Location | `clients/go/README.md:136-137` |
| Status | Resolved |
**Description:** The README "Write Semantics" section states:
> The CLI exposes the same command as `advise-supervisory`, and `write` / `write2` take `--user-id`.
The Go CLI has no standalone `write2` command — only `write2-bulk`. The analogous statement in the Python, Rust, and .NET README is accurate because those CLIs do expose `write2` as a standalone subcommand. A Go caller following this doc and attempting `mxgw-go write2 -session-id ... -type int32 -value 42 -timestamp 2026-01-01T00:00:00Z` receives `unknown command "write2"` (routed to the default branch of `run()`), not the expected MXAccess Write2 call.
**Recommendation:** Change the sentence to accurately reflect the Go CLI surface, e.g.: "The CLI exposes the same command as `advise-supervisory`, and `write` takes `-user-id`." If a standalone `write2` command is intended for cross-client parity, add it (mirroring `runWrite` with the addition of a `-timestamp` flag and a `Write2Raw`/`Write2` SDK call).
**Resolution:** 2026-06-18 — Confirmed root cause: Go CLI has no `write2` case in the `runWithIO` switch and no `runWrite2` function; only `write2-bulk` exists. Changed the sentence in `clients/go/README.md` from "The CLI exposes the same command as `advise-supervisory`, and `write` / `write2` take `--user-id`." to "The CLI exposes the same command as `advise-supervisory`, and `write` takes `-user-id`." No standalone `write2` command added (cross-client parity decision deferred to a future change). `go build ./...` and `go test ./...` green.
+87 -2
View File
@@ -4,8 +4,8 @@
|---|---|
| Module | `clients/java` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
@@ -123,6 +123,31 @@ Re-review of the Java client delta: the §8 `GalaxyClientFactory` seam, `InProce
| 9 | Testing coverage | Client.Java-045, Client.Java-046 |
| 10 | Documentation & comments | Client.Java-047, Client.Java-048 |
### 2026-06-18 review (commit 88915c3)
Re-review pass at `88915c3`. Diff against `8df5ab3` is six commits touching
`clients/java`: `8df0479` / `bdb7e14` / `8cebe43` / `bed647c` (Client.Java-040..048
fixes — control-character JSON escaping, stream-alarms terminal-slot fix, async
overflow flood test, `InProcessGatewayHarness` Javadoc, Javadoc corrections,
and `MxGatewayClientVersion` bump to 0.1.1); `9eedf9d` (parity-gotchas docs +
`advise-supervisory` CLI subcommand across all language clients);
`e7b8aa6` (Java `writeArrayElements` default-fill SDK helper + session test);
`88915c3` (version bump `0.1.1 → 0.1.2` in `build.gradle`). Generated protobuf
Java (`src/main/generated/`) excluded from review — build churn only.
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | No issues found. `writeArrayElements` builds the `MxSparseArray` correctly: `elementDataType`, `totalLength`, and elements iterated via `TreeMap` for deterministic ascending order match the Go/Rust/Python/dotnet reference implementations. The `MxValues.decode` `SPARSE_ARRAY_VALUE -> null` arm is sound — the type is write-only and never returned by the gateway; returning `null` is the correct sentinel (matches `KIND_NOT_SET`). |
| 2 | mxaccessgw conventions | No issues found. `advise-supervisory` routes through `invokeCommand` using `MX_COMMAND_KIND_ADVISE_SUPERVISORY` — no MXAccess COM touched in the client, generated code untouched. |
| 3 | Concurrency & thread safety | No issues found. The `stream-alarms` terminal-slot rework (`AtomicBoolean terminated` + `AtomicReference<Object> terminal`) is a sound first-terminal-wins design. The poll-then-check-terminal drain loop is correct for the `terminal.set` publish ordering (`terminated=true` is set before `terminal.set(item)`, but the drain only reads `terminal` when `poll` returns null, so a retry on the next 50ms poll sees it). |
| 4 | Error handling & resilience | No issues found. `writeArrayElements` propagates transport/protocol errors via the existing `writeRaw` / `invokeCommand` path and its `MxGatewayException` contract. |
| 5 | Security | No issues found. No new auth surface, no logging of values or credentials. |
| 6 | Performance & resource management | No issues found. `new TreeMap<>(elements)` makes a defensive copy for deterministic iteration — correct and cheap for practical element counts. |
| 7 | Design-document adherence | No issues found. `writeArrayElements` delegates to `writeRaw`, which ultimately routes through the normal `MX_COMMAND_KIND_WRITE` path — MXAccess parity is preserved; the gateway expands the sparse descriptor, not the client. |
| 8 | Code organization & conventions | Issue found: `build.gradle` bumped to `0.1.2` but `MxGatewayClientVersion.CLIENT_VERSION` remains `"0.1.1"` and the tests assert `0.1.1` — same version-split as resolved Client.Java-044 (Client.Java-049). |
| 9 | Testing coverage | Issue found: the new `advise-supervisory` CLI subcommand has a `FakeSession` stub but no dedicated CLI-level test (Client.Java-050). |
| 10 | Documentation & comments | Issue found: `writeArrayElements` Javadoc documents `[0, totalLength)` index contract and `totalLength > 0` as required, but no client-side `IllegalArgumentException` is thrown for violations — only the Javadoc describes the constraint; Java `int` silently sign-extends to a large `uint32` on the wire for negative inputs (Client.Java-051). README dependency example still shows `0.1.1` (cross-ref Client.Java-049). |
## Findings
### Client.Java-001
@@ -896,3 +921,63 @@ BrowseChildrenReply reply = galaxy.browseChildren(
**Recommendation:** Add a `PROVIDER_STATUS` arm to `formatAlarmFeedMessage` that renders the provider status (mode / degraded / reason) consistently with the other alarm-feed arms — do not add a `default ->` that silently drops it, since the provider status is meaningful and the exhaustive switch is the compiler-enforced guard that catches exactly this kind of future contract drift.
**Resolution:** 2026-06-15 — Confirmed via `gradle :zb-mom-ww-mxgateway-cli:compileJava` failing with "the switch expression does not cover all possible input values" at `MxGatewayCli.java:1699` on the Windows host. Added a `case PROVIDER_STATUS ->` arm to `formatAlarmFeedMessage` yielding `provider-status mode=%s degraded=%b reason=%s` (from `AlarmProviderStatus.getMode().name()` / `getDegraded()` / `getReason()`), plus the `import mxaccess_gateway.v1.MxaccessGateway.AlarmProviderStatus;`. No `default` arm — the exhaustive switch expression remains the compile-time guard against future `payload` oneof additions. Verified `gradle test` builds and passes on the Windows host (Java 21).
### Client.Java-049
| Field | Value |
|---|---|
| Severity | Low |
| Category | Code organization & conventions |
| Location | `clients/java/build.gradle:16`, `clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientVersion.java:12`, `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java:59,89`, `clients/java/README.md:399` |
| Status | Resolved |
**Description:** Commit `88915c3` (`chore(clients): bump all five clients 0.1.1 -> 0.1.2`) incremented `build.gradle` `version = '0.1.2'` but left `MxGatewayClientVersion.CLIENT_VERSION = "0.1.1"` unchanged. The two CLI test assertions that check the version string also still assert `0.1.1` (lines 59 and 89 of `MxGatewayCliTests.java`), and the `README.md` Maven dependency example at line 399 shows `:0.1.1`. The published Gradle artifact carries version `0.1.2` (from `build.gradle`) while the `version` CLI command reports `mxgateway-java 0.1.1` and the README tells a consumer to depend on `:0.1.1`. Same class of version drift as the resolved Client.Java-044 (where `0.1.0` vs `0.1.1` was the split) — the fix for Client.Java-044 bumped `CLIENT_VERSION` to `"0.1.1"` but the `build.gradle` bump to `0.1.2` was not accompanied by a matching `MxGatewayClientVersion` update.
**Recommendation:** Bump `CLIENT_VERSION` to `"0.1.2"` in `MxGatewayClientVersion.java`, update the two `MxGatewayCliTests` assertions from `0.1.1` to `0.1.2`, and update the `README.md` dependency example coordinate to `:0.1.2`. Consider sourcing `CLIENT_VERSION` from a Gradle-generated resource file (e.g. via `processResources` task writing `version.properties`) so the two version strings cannot drift again.
**Resolution:** 2026-06-18 — Confirmed: `build.gradle` already at `0.1.2` while `CLIENT_VERSION` was still `"0.1.1"` and test assertions/README matched the old value. Bumped `CLIENT_VERSION` to `"0.1.2"` in `MxGatewayClientVersion.java`, updated both version assertions in `MxGatewayCliTests.java` (plain-text and JSON paths), and updated the Maven dependency coordinate in `README.md` to `:0.1.2`. No new test needed — the two existing assertions (`versionCommandPrintsProtocolVersions`, `versionCommandPrintsJson`) now exercise the corrected value. (pending windev gradle verification)
### Client.Java-050
| Field | Value |
|---|---|
| Severity | Low |
| Category | Testing coverage |
| Location | `clients/java/zb-mom-ww-mxgateway-cli/src/main/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCli.java:1046-1068` (new `AdviseSupervisoryCommand`), `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java:1306-1313` (stub) |
| Status | Resolved |
**Description:** Commit `9eedf9d` added the `advise-supervisory` CLI subcommand (`AdviseSupervisoryCommand`) to all language client CLIs. The Java `FakeSession.adviseSupervisoryRaw` stub was added to `MxGatewayCliTests` but no test exercises the new subcommand path. There is no test that calls `execute(factory, "advise-supervisory", "--session-id", "s", "--server-handle", "1", "--item-handle", "2")` and asserts the command routes through `session.adviseSupervisoryRaw`, produces a non-zero exit code on failure, or emits the correct JSON / text output. The `adviseCalled` field shared with `adviseRaw` means even an indirect smoke path that calls `advise` could mask a missing `adviseSupervisory` wire. Every other new CLI subcommand in this diff has a dedicated CLI-level test (the `writeArrayElements` helper has a session-level test in `MxGatewayClientSessionTests`).
**Recommendation:** Add a `@Test void adviseSupervisoryCommandCallsAdviseSupervisoryRaw()` to `MxGatewayCliTests` that exercises the subcommand via `execute(factory, "advise-supervisory", "--session-id", "s", "--server-handle", "12", "--item-handle", "34")` and asserts exit code 0, that `factory.client.session.adviseCalled` (or a dedicated `adviseSupervisoryCalled` boolean) is true, and that the output contains the reply kind string `MX_COMMAND_KIND_ADVISE_SUPERVISORY`. Consider renaming `adviseCalled` to `adviseSupervisoryCalled` for the `adviseSupervisoryRaw` stub (a separate `adviseCalled` for `adviseRaw`) to prevent future tests from masking each other.
**Resolution:** 2026-06-18 — Confirmed: `adviseSupervisoryRaw` stub existed in `FakeSession` but shared `adviseCalled` with the plain `adviseRaw` stub, and no test exercised the `advise-supervisory` subcommand path. Added a dedicated `adviseSupervisoryCalled` boolean field to `FakeSession` and wired it to the `adviseSupervisoryRaw` stub (severing the shared flag that masked routing). Added `adviseSupervisoryCommandCallsAdviseSupervisoryRaw` test in `MxGatewayCliTests.java` that invokes `execute(factory, "advise-supervisory", "--session-id", "session-cli", "--server-handle", "12", "--item-handle", "34", "--json")` and asserts exit code 0, `adviseSupervisoryCalled` is true, `adviseCalled` is false (verifying routing isolation), and output contains `"kind":"MX_COMMAND_KIND_ADVISE_SUPERVISORY"`. (pending windev gradle verification)
### Client.Java-051
| Field | Value |
|---|---|
| Severity | Low |
| Category | Documentation & comments |
| Location | `clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java:622-657` |
| Status | Resolved |
**Description:** `writeArrayElements` accepts `int totalLength` and `Map<Integer, MxValue> elements` whose keys are plain Java `int`. The proto fields `MxSparseArray.total_length` and `MxSparseElement.index` are both `uint32`. Java's protobuf runtime maps `uint32` to `int` (Java has no unsigned primitive), so passing a negative value to `setTotalLength(int)` or `setIndex(int)` silently sets the wire field to the two's-complement reinterpretation (e.g. `-1` → `4294967295`). The gateway will likely reject the resulting request with `INVALID_ARGUMENT`, but the error message will reference a large `uint32` value rather than the caller's negative `int`, making the failure hard to diagnose. The Javadoc states "supplied indices must be within `[0, totalLength)`" and "`totalLength` is required" but does not state what happens with negative inputs, and no `IllegalArgumentException` is thrown. All other language clients use unsigned types (`uint`, `uint32`, `u32`) that prevent negatives at the type level; Java cannot replicate that, so explicit validation is the correct substitute. The Python client is similarly unvalidated and its docstring explicitly defers to the gateway for rejection — but Python's `grpc` runtime raises an internal exception on negative `uint32` fields before the network call, so it fails more obviously than Java's silent wire wrap.
**Recommendation:** Add client-side guards before the `MxSparseArray.Builder` population:
```java
if (totalLength <= 0) {
throw new IllegalArgumentException("totalLength must be > 0, got " + totalLength);
}
for (Map.Entry<Integer, MxValue> entry : elements.entrySet()) {
int idx = entry.getKey();
if (idx < 0 || idx >= totalLength) {
throw new IllegalArgumentException(
"element index " + idx + " is out of range [0, " + totalLength + ")");
}
}
```
Add a test in `MxGatewayClientSessionTests` asserting both `IllegalArgumentException` paths (negative `totalLength`, negative/out-of-range index). Duplicate-index detection can be left to the gateway (the proto `repeated` field allows duplicates, and the gateway can sort out semantics).
**Resolution:** 2026-06-18 — Confirmed: `writeArrayElements` passed negative `int` values straight to `setTotalLength`/`setIndex` with no guard, silently producing large `uint32` wire values. Added `if (totalLength <= 0) throw new IllegalArgumentException(...)` and a per-entry `if (idx < 0 || idx >= totalLength) throw new IllegalArgumentException(...)` loop before the proto builder in `MxGatewaySession.writeArrayElements`. Updated Javadoc to document the new `@throws IllegalArgumentException` contract and the uint32 unsigned-type rationale. Added two tests in `MxGatewayClientSessionTests`: `writeArrayElementsRejectsNonPositiveTotalLength` (covers negative and zero `totalLength`) and `writeArrayElementsRejectsOutOfRangeIndex` (covers negative index, index equal to `totalLength`, and index above `totalLength`). (pending windev gradle verification)
+72 -2
View File
@@ -4,13 +4,41 @@
|---|---|
| Module | `clients/python` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
## Checklist coverage
### 2026-06-18 re-review (commit 88915c3)
Re-review of the Python client delta at `88915c3` over base `8df5ab3`. Feature
scope: `Session.write_array_elements` default-fill sparse-array helper, the new
`advise-supervisory` CLI subcommand, prior 032–036 fixes carried, export
additions for `BrowseChildrenOptions` / `LazyBrowseNode`, version bump 0.1.1 →
0.1.2, README "Write Semantics" doc section, and the corresponding generated
`mxaccess_gateway_pb2.py` descriptor update.
Generated-file churn check (memory `project_python_client_regen_pin`): only
`mxaccess_gateway_pb2.py` changed, exactly one DESCRIPTOR line was replaced
(adding the `MxSparseArray` / `MxSparseElement` encoding), and the
`Protobuf Python Version` header remained `6.31.1` at both commits. No
spurious grpcio version churn was introduced.
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | Client.Python-037 |
| 2 | mxaccessgw conventions | No issues found |
| 3 | Concurrency & thread safety | No issues found |
| 4 | Error handling & resilience | No issues found |
| 5 | Security | No issues found |
| 6 | Performance & resource management | No issues found |
| 7 | Design-document adherence | No issues found |
| 8 | Code organization & conventions | No issues found |
| 9 | Testing coverage | Client.Python-038 |
| 10 | Documentation & comments | No issues found |
### 2026-06-16 re-review (commit 8df5ab3)
Re-review of the Python client delta: new galaxy CLI commands, options.py TLS/auth, large test additions. Prior Client.Python-027..031 confirmed resolved. One claimed regression (Python-004 dead variable) and one Medium README/API mismatch.
@@ -1530,3 +1558,45 @@ passed, 1 skipped, 0 warnings; previously 1 warning). The `tls`-marked
**Recommendation:** Update the example/prose to `browse_children_raw(...)` (and promote the high-level `browse()`/`LazyBrowseNode` path), or add a `browse_children` alias. Add a `hasattr` test to catch future renames.
**Resolution:** 2026-06-16 — Updated the README "Browsing lazily" prose and example to `browse_children_raw(...)` and added a pointer to the higher-level `browse()`/`LazyBrowseNode` walker. Tests: `test_galaxy_client_exposes_browse_children_raw` (hasattr guard) and `test_readme_browse_example_uses_existing_method` (parses every `galaxy.<method>()` call in README against the client class) in `tests/test_review_findings_032_to_036.py`.
### Client.Python-037
| Field | Value |
|---|---|
| Severity | Low |
| Category | Correctness & logic bugs |
| Location | `clients/python/pyproject.toml:10` |
| Status | Resolved |
**Description:** The `description` field in `pyproject.toml` reads `"Async Python client scaffold for MXAccess Gateway."` at commit `88915c3`. Client.Python-001 resolved this on 2026-05-18 by removing the word "scaffold". The fix was lost when commit `397d3c5` (the package directory rename, `src/mxgateway` → `src/zb_mom_ww_mxgateway`) re-created `pyproject.toml` from scratch, re-introducing the stale wording. The version bump commit `88915c3` carried the regression forward without correcting it.
The issue is purely cosmetic and does not affect the wheel build or runtime behaviour, but the "scaffold" label misrepresents the maturity of a fully-implemented, versioned package to anyone reading PyPI metadata. It is also a direct regression of a previously-resolved finding.
**Recommendation:** Change the `description` in `clients/python/pyproject.toml` from `"Async Python client scaffold for MXAccess Gateway."` to `"Async Python client for MXAccess Gateway."` (drop "scaffold"), matching the fix applied under Client.Python-001. The `test_pip_wheel_build_succeeds` test will confirm the wheel still builds; no additional test is needed for a pure metadata word change.
**Resolution:** 2026-06-18 — Root cause confirmed: `pyproject.toml` line 10 still contained "scaffold" at commit `88915c3`. Removed "scaffold" from the `description` field so it now reads `"Async Python client for MXAccess Gateway."`, matching the Client.Python-001 fix and the sibling client descriptions. Added `test_pyproject_description_does_not_contain_scaffold` in `tests/test_review_findings_037_038.py` to prevent future regressions; the test failed before the fix and passes after. Full suite: 127 passed, 1 skipped. Generated directory unchanged.
### Client.Python-038
| Field | Value |
|---|---|
| Severity | Low |
| Category | Testing coverage |
| Location | `clients/python/tests/`, `clients/python/src/zb_mom_ww_mxgateway_cli/commands.py:280-299,742-758` |
| Status | Resolved |
**Description:** The new `advise-supervisory` CLI subcommand (commit `88915c3`) has no test coverage — not even a `--help` smoke registration test of the kind added for `stream-alarms` (`test_stream_alarms_is_registered`) or the earlier `advise` command. There is no test that:
1. Asserts `advise-supervisory` is registered as a subcommand on `main` (i.e. a `--help` round-trip through `CliRunner` that confirms the subcommand name exists and Click does not report `no such command`).
2. Drives `_advise_supervisory` through `CliRunner` with a fake stub injected via monkeypatched `GatewayClient.connect` and asserts (a) the captured `MxCommand` has `kind == MX_COMMAND_KIND_ADVISE_SUPERVISORY` and (b) `server_handle`/`item_handle` are forwarded correctly.
The README mentions `advise-supervisory` in prose (`"The CLI exposes the same command as advise-supervisory"`) but provides no `mxgw-py advise-supervisory …` example line, so the existing `test_readme_alarm_examples_parse_against_cli` scanner does not exercise it. A silent renaming or option drift would go undetected.
The pattern to follow is `test_cli_acknowledge_alarm_happy_path` in `tests/test_review_findings_022_to_026.py`, extended with a `MX_COMMAND_KIND_ADVISE_SUPERVISORY` assertion.
**Recommendation:** Add to `tests/test_review_findings_032_to_036.py` (or a new `tests/test_review_findings_037_038.py`):
1. `test_advise_supervisory_is_registered` — `CliRunner().invoke(main, ["advise-supervisory", "--help"])` asserts exit code 0 and "AdviseSupervisory" (or the help text) is present.
2. `test_cli_advise_supervisory_happy_path` — injects a fake stub via `monkeypatch`, drives `advise-supervisory --session-id s1 --server-handle 1 --item-handle 2 --json`, and asserts the captured `MxCommand.kind == MX_COMMAND_KIND_ADVISE_SUPERVISORY`, `advise_supervisory.server_handle == 1`, `advise_supervisory.item_handle == 2`.
**Resolution:** 2026-06-18 — Root cause confirmed: no test existed for `advise-supervisory` despite it being registered and implemented at commit `88915c3`. Added `tests/test_review_findings_037_038.py` with three tests: `test_advise_supervisory_is_registered` (CliRunner `--help` round-trip asserting exit 0 and `--server-handle`/`--item-handle` in output) and `test_cli_advise_supervisory_happy_path` (monkeypatched `GatewayClient.connect` with a fake stub, drives the CLI end-to-end, asserts `MxCommand.kind == MX_COMMAND_KIND_ADVISE_SUPERVISORY` and `advise_supervisory.server_handle == 7`, `advise_supervisory.item_handle == 42`). No source change was required — the command implementation was correct. Full suite: 127 passed, 1 skipped. Generated directory unchanged.
+77 -2
View File
@@ -4,8 +4,8 @@
|---|---|
| Module | `clients/rust` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
@@ -132,6 +132,27 @@ Re-review of the Rust client delta: options.rs TLS trust decision, mxgw-cli gala
| 9 | Testing coverage | Client.Rust-038 |
| 10 | Documentation & comments | No issues found |
### 2026-06-18 review (commit 88915c3)
Re-review of `git diff 8df5ab3..88915c3 -- clients/rust/`. The diff introduces: `Session::write_array_elements` sparse-array default-fill helper (`src/session.rs`); `SparseArrayValue` → `Unset` decode mapping in `MxValueProjection` (`src/value.rs`); `advise-supervisory` CLI subcommand (`crates/mxgw-cli/src/main.rs`); README and `RustClientDesign.md` docs additions; version bump 0.1.1 → 0.1.2; and a suite of tests in `tests/client_behavior.rs`.
Known prior bug (commit `72cf2f4`): `write_array_elements` set the outer `ProtoMxValue.data_type` to the element type — confirmed fixed via `..ProtoMxValue::default()` (outer `data_type = 0`). The e2e test `write_array_elements_routes_sparse_array_write_through_fake_gateway` asserts `value.data_type == 0` and `sparse.element_data_type == Integer`, correctly locking the fix in. The `MxValue` roundtrip is sound: `MxValue::from_proto(sparse_value).into_proto()` returns the original raw proto unchanged, so the sparse payload reaches the wire unmodified.
All prior findings 033–038 confirmed Resolved at `8df5ab3`. `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, and `cargo test --workspace` are assumed clean at HEAD (source review only; toolchain is Windows-only and not available on this macOS host).
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | Issue found (Client.Rust-040): the `sparse_int32_value` unit-test helper sets `data_type: MxDataType::Integer as i32` on the outer `MxValue` but `write_array_elements` uses `..ProtoMxValue::default()` (outer `data_type = 0`); the helper comment claims it builds "the proto MxValue that `write_array_elements` would send" so the unit tests using it test a subtly incorrect shape. The e2e test correctly covers the fix, but the unit test helper should match the implementation. |
| 2 | mxaccessgw conventions | No issues found — `advise-supervisory` goes through `session.invoke` which calls `command_request`, which calls `next_correlation_id` internally; unique per-call correlation ids are preserved. `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` are expected clean (no new lint-tripping patterns introduced). |
| 3 | Concurrency & thread safety | No issues found — `write_array_elements` is a thin synchronous builder that delegates to the existing `Session::write` async path; `last_write_command` in `FakeState` is behind a `Mutex<Option<_>>` and accessed correctly. No new `unsafe`, no new shared mutable state. |
| 4 | Error handling & resilience | No issues found — `total_length = 0`, out-of-range indices, duplicate indices, and element-kind mismatches are all validated by the gateway's `SparseArrayExpander` and surface as `Error::InvalidArgument` (propagated, per the doc comment). No client-side guard is needed; the gateway is the single validation point. |
| 5 | Security | No issues found — `write_array_elements` passes `user_id` through to `Session::write` which is already covered by the existing API-key + scope enforcement path; no credentials or secrets in the new surface. |
| 6 | Performance & resource management | No issues found — `impl IntoIterator<Item = (u32, MxValue)>` avoids requiring an intermediate `Vec`; elements are collected once into `Vec<MxSparseElement>` and immediately handed to the proto. No unnecessary clones on the hot path. |
| 7 | Design-document adherence | Issue found (Client.Rust-039): `Session::write_array_elements` is a new public SDK method and `advise-supervisory` is a new CLI subcommand; neither appears in `RustClientDesign.md` (Session API block or CLI commands table). CLAUDE.md requires docs to change in the same commit as the source. README was correctly updated. |
| 8 | Code organization & conventions | No issues found — `register_page_token` was cleanly extracted from `browse_children_one_level` and covered with a unit test. `write_array_elements` is placed adjacent to `write` in `session.rs`. The `WriteOk` `InvokeOverride` variant and `last_write_command` capture are well-scoped to the test infrastructure. |
| 9 | Testing coverage | Cross-referenced with Client.Rust-040: the `sparse_int32_value` test helper tests a proto shape with incorrect outer `data_type`; the unit tests using it do not verify `data_type` and would not catch a regression of the outer-`data_type` fix. The e2e test `write_array_elements_routes_sparse_array_write_through_fake_gateway` does assert `data_type == 0` and provides the real regression guard. |
| 10 | Documentation & comments | No issues found — README `write_array_elements` and `advise-supervisory` sections are accurate. The `SparseArrayValue` → `Unset` comment in `value.rs` explains the write-only rationale clearly. The `write_array_elements` doc comment correctly describes the "not a preserve, a reset" semantics. The README Rust code example for `advise-supervisory` omits `use` imports for `Payload`/`MxCommandKind`/`AdviseSupervisoryCommand` but this is consistent with other README code-snippet conventions across all five clients. |
## Findings
### Client.Rust-001
@@ -869,3 +890,57 @@ This is masked by the tests: `tls_with_require_certificate_validation_does_not_s
**Recommendation:** Add unit tests for all three (none need a network connection).
**Resolution:** 2026-06-16 — Added all three test groups. (1) `--tls`/`--plaintext` resolution: `connection_defaults_to_plaintext`, `connection_tls_flag_disables_plaintext`, `connection_plaintext_flag_selects_plaintext`, `connection_rejects_tls_and_plaintext_together`. (2) Extracted the page-token dedup guard into pure `register_page_token` and covered it with `register_page_token_accepts_distinct_tokens_and_rejects_repeats`. (3) RFC3339 error paths: `rfc3339_parser_rejects_trailing_characters`, `rfc3339_parser_rejects_day_zero`, `rfc3339_parser_rejects_month_thirteen`, `rfc3339_parser_rejects_day_out_of_range_for_month`.
### Client.Rust-039
| Field | Value |
|---|---|
| Severity | Low |
| Category | Design-document adherence |
| Location | `clients/rust/RustClientDesign.md:101-131` (Session API block); `clients/rust/RustClientDesign.md:326-353` (CLI commands table) |
| Status | Resolved |
**Description:** The diff adds two pieces of new public surface that are not reflected in `RustClientDesign.md`:
1. `Session::write_array_elements` — a new public async method in `clients/rust/src/session.rs:567-601`. It accepts `element_data_type: MxDataType`, `total_length: u32`, and `elements: impl IntoIterator<Item = (u32, MxValue)>` alongside the standard `server_handle`/`item_handle`/`user_id`. The Session API block in `RustClientDesign.md` (lines 101-131) lists every other `Session` method but omits `write_array_elements`.
2. `Command::AdviseSupervisory` — a new CLI subcommand (`clients/rust/crates/mxgw-cli/src/main.rs:203-214`, dispatch at lines 663-683). The CLI commands table in `RustClientDesign.md` (lines 326-353) lists every other subcommand but does not include `advise-supervisory`.
CLAUDE.md requires "When public APIs … change, the affected docs … must change in the same commit."
**Recommendation:** Add `write_array_elements` to the Session block:
```rust
pub async fn write_array_elements(
&self,
server_handle: i32,
item_handle: i32,
element_data_type: MxDataType,
total_length: u32,
elements: impl IntoIterator<Item = (u32, MxValue)>,
user_id: i32,
) -> Result<(), Error>;
```
Add a sentence noting that the `elements` iterator accepts `(index, value)` pairs (not a `HashMap`, so duplicate indices are forwarded to the gateway, which rejects them with `InvalidArgument`). Add `mxgw advise-supervisory --session-id <id> --server-handle <h> --item-handle <h>` to the CLI table.
**Resolution:** 2026-06-18 — Added `write_array_elements` (with its exact `session.rs` signature) to the Session API block in `RustClientDesign.md` between `write2` and `write_bulk`. Added `mxgw advise-supervisory --session-id <id> --server-handle <h> --item-handle <h>` to the CLI commands table after `mxgw advise`. Both signatures verified against `clients/rust/src/session.rs:567` and `clients/rust/crates/mxgw-cli/src/main.rs:109-120`. `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, and `cargo test --workspace` all pass.
### Client.Rust-040
| Field | Value |
|---|---|
| Severity | Low |
| Category | Testing coverage |
| Location | `clients/rust/tests/client_behavior.rs:1195-1224` (`sparse_int32_value` helper); `clients/rust/tests/client_behavior.rs:1226-1264` (unit tests using the helper) |
| Status | Resolved |
**Description:** The `sparse_int32_value` test helper (lines 1195-1224) carries this comment: "Build the proto `MxValue` that `write_array_elements` would send." It then constructs the outer `MxValue` with `data_type: MxDataType::Integer as i32` (line 1215). However, `write_array_elements` in `session.rs` uses `..ProtoMxValue::default()` for the outer value, which sets `data_type` to `0` (= `MxDataType::Unspecified`). The helper builds the old, incorrect shape that the known bug fix (`72cf2f4`) explicitly corrected — the outer `data_type` should carry the element type only inside `SparseArray.element_data_type`, not on the enclosing `MxValue`.
The two unit tests that use this helper (`write_array_elements_proto_shape_has_sparse_oneof_kind` at line 1226 and `write_array_elements_empty_elements_is_valid_all_defaults` at line 1253) do not assert `data_type` on the outer `MxValue`, so they pass and do not catch the discrepancy. The only test that asserts `value.data_type == 0` is the e2e test `write_array_elements_routes_sparse_array_write_through_fake_gateway`, which correctly locks in the fix. The unit tests therefore give a false sense of coverage: they document and confirm a shape that does not match the implementation's actual output.
If the `..ProtoMxValue::default()` line were ever accidentally changed back to set `data_type` from `element_data_type`, the unit tests would continue to pass while the e2e test would catch the regression — but the test comment explicitly says the helper represents "what `write_array_elements` would send," making the incorrect `data_type` in the helper actively misleading for future maintainers.
**Recommendation:** Fix the `sparse_int32_value` helper to use `..MxValue::default()` (which zeros `data_type`) instead of `data_type: MxDataType::Integer as i32`, so the helper accurately represents the wire shape `write_array_elements` actually emits. Then add an explicit `assert_eq!(proto.data_type, 0, "outer MxValue.data_type must be Unspecified")` assertion to `write_array_elements_proto_shape_has_sparse_oneof_kind` so the unit test also locks in the outer-`data_type` fix — providing a second, faster regression guard that does not require spinning up a fake gRPC server.
**Resolution:** 2026-06-18 — Root cause confirmed: `sparse_int32_value` set `data_type: MxDataType::Integer as i32` on the outer `MxValue`, contradicting the `..ProtoMxValue::default()` in `Session::write_array_elements` which leaves `data_type = 0`. Fixed the helper to use `..MxValue::default()` (removing the explicit `data_type` field), so the outer `MxValue.data_type` is now `0` (Unspecified), matching the actual wire shape. Added `assert_eq!(proto.data_type, 0, …)` assertions to all three unit tests that call the helper: `write_array_elements_proto_shape_has_sparse_oneof_kind`, `write_array_elements_empty_elements_is_valid_all_defaults`, and `sparse_array_value_round_trips_through_client_mx_value_projection_as_unset`. All 36 tests pass (`cargo test --workspace`); `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` are clean.
+81 -2
View File
@@ -4,8 +4,8 @@
|---|---|
| Module | `src/ZB.MOM.WW.MxGateway.Contracts` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
@@ -470,3 +470,82 @@ Re-review of the proto delta (`git diff 410acc9..8df5ab3 -- .../Protos/`): the n
**Recommendation:** Add a round-trip test setting `MxEvent.ReplayGap` with both sequence fields, asserting `BodyCase == None`, plus a descriptor assertion pinning `ReplayGapFieldNumber == 14` and the `ReplayGap` field numbers (1, 2).
**Resolution:** _(2026-06-16)_ Added `ProtobufContractRoundTripTests.MxEvent_RoundTripsReplayGapSentinelAndPinsFieldNumbers` to `ProtobufContractRoundTripTests.cs`. The test pins `MxEvent.ReplayGapFieldNumber == 14` via the generated constant, pins `ReplayGap.RequestedAfterSequenceFieldNumber == 1` and `ReplayGap.OldestAvailableSequenceFieldNumber == 2` via `ReplayGap.Descriptor.Fields` (asserting both the number and the field name), builds a sentinel `MxEvent` with both sequence fields populated and no body oneof set, serializes and parses it, then asserts both sequence values survive and `BodyCase == None` (confirming `replay_gap` is orthogonal to the body oneof).
#### 2026-06-18 review (commit 88915c3)
Re-review pass at `88915c3` scoped to the contract changes since `8df5ab3`
(`git diff 8df5ab3..88915c3 -- src/ZB.MOM.WW.MxGateway.Contracts/`). The
window contains exactly one contract feature commit: the array-write-ergonomics
addition (`MxSparseArray`, `MxSparseElement`, `sparse_array_value = 19` on
`MxValue`). Also included: a minor version bump (`0.1.1` → `0.1.2` in
`ZB.MOM.WW.MxGateway.Contracts.csproj`), regenerated `Generated/MxaccessGateway.cs`
(build output — confirmed consistent with the proto; `SparseArrayValueFieldNumber =
19` and the new generated class registrations match the proto declaration), and
the removal of the stale "Task 12 / contract surface only" parenthetical from the
`replay_gap` field comment (Contracts-021 resolution already covered in the
`8df5ab3` pass; the diff shows the cleaned comment). `mxaccess_worker.proto` and
`galaxy_repository.proto` are unchanged.
Verified against `docs/plans/2026-06-18-array-write-ergonomics-design.md`,
`gateway.md` (section "MxSparseArray — default-fill partial array writes"),
and `docs/WorkerConversion.md` (section "Sparse array expansion").
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | No issues found. Field number `sparse_array_value = 19` is new and does not collide with any existing arm (18 = `raw_value`, 17 = `array_value`). `MxSparseArray` field numbers 1/2/3 and `MxSparseElement` field numbers 1/2 are all fresh. The `MxValue` oneof arms 10-18 are unchanged. The additive-only invariant is honoured. The generated `SparseArrayValueFieldNumber = 19` constant matches the proto. The `MxSparseElement.value` field reuses `MxValue`, which allows a client to nest another `sparse_array_value` inside an element — a recursive structure the gateway will reject at validation time but the proto level cannot prevent. This is a documentation gap (see Contracts-023) rather than a correctness bug in the contract itself, since gateway validation is the documented enforcement point. |
| 2 | mxaccessgw conventions | No issues found. Wire-compatibility policy comment block at the top of `mxaccess_gateway.proto` (Contracts-005) remains intact and this change honours it. Naming follows conventions: `snake_case` fields, `PascalCase` messages, no enum-prefix needed (no new enums). The `MxSparseArray` message-level comment clearly states write-only semantics and that the worker never receives it. Generated code regenerated, not hand-edited. |
| 3 | Concurrency & thread safety | N/A — pure contract definitions plus a static constants class. |
| 4 | Error handling & resilience | No issues found. The validation rules (`total_length == 0`, `index >= total_length`, duplicate indices, unsupported `element_data_type`, element-kind mismatch) are documented in `gateway.md` and `docs/plans/2026-06-18-array-write-ergonomics-design.md`; they are not expressed in the proto itself, which is correct for proto3. The write-only guard (reject on read/event paths) is documented at the proto message level. |
| 5 | Security | No issues found. No new credential-bearing fields. `MxSparseElement.value` carries the same write-value surface as any other `MxValue` write field; credential-sensitivity comments already on `WriteSecuredCommand.value` / `WriteSecured2Command.value` / the corresponding bulk entry fields apply to any write value, including sparse. No new redaction gap. |
| 6 | Performance & resource management | No issues found. `repeated MxSparseElement elements` is sent once per write; the gateway's expansion to a full `MxArray` is gateway-side only and the worker receives a normal whole-array value. No proto-level bloat or unbounded repeated field beyond what already exists on `MxArray`. |
| 7 | Design-document adherence | No drift. The shipped proto matches the design document (`docs/plans/2026-06-18-array-write-ergonomics-design.md`) field-for-field: `element_data_type = 1`, `total_length = 2`, `elements = 3` on `MxSparseArray`; `index = 1`, `value = 2` on `MxSparseElement`; `sparse_array_value = 19` on `MxValue`. `gateway.md` section "MxSparseArray" and `docs/WorkerConversion.md` are both updated and consistent. `docs/Contracts.md` has no mention of the new value arm — see Contracts-024. |
| 8 | Code organization & conventions | No issues found. The `csharp_namespace` option and protobuf `package` are unchanged. The new messages are placed after `MxArray` and its typed-array sub-messages, which is the correct locality. No message is inserted between existing numeric-series messages. Version bump `0.1.1` → `0.1.2` is appropriate for a minor additive change. |
| 9 | Testing coverage | Issues found: Contracts-023 — no `ProtobufContractRoundTripTests` coverage exists for `MxSparseArray`, `MxSparseElement`, or `MxValue.KindOneofCase.SparseArrayValue` (field number 19). This is the same gap class as Contracts-007/010/018/022. |
| 10 | Documentation & comments | Issues found: Contracts-024 (`docs/Contracts.md` has no mention of `MxSparseArray` — the canonical contracts document undercounts the public value surface); Contracts-025 (`GatewayContractInfoTests.GatewayProtocolVersion_IsVersionThree` summary enumerates alarm and bulk write/read extensions under version 3 but not the sparse array addition, leaving future readers without guidance on whether the new arm also ships under version 3 without a bump). |
### Contracts-023
| Field | Value |
|---|---|
| Severity | Low |
| Category | Testing coverage |
| Location | `src/ZB.MOM.WW.MxGateway.Tests/Contracts/ProtobufContractRoundTripTests.cs` |
| Status | Resolved |
**Description:** No round-trip test or descriptor pin exists for the new `MxSparseArray` message, `MxSparseElement` message, or `MxValue.KindOneofCase.SparseArrayValue` (field number 19). A future renumber or type-narrowing of `sparse_array_value = 19`, or of `MxSparseArray`'s field numbers (1/2/3) or `MxSparseElement`'s field numbers (1/2), would not be caught at the contract level. This is the same gap class as Contracts-007 (`MxValue.raw_value`), Contracts-010 (bulk write/read), Contracts-018 (alarm-provider fallback), and Contracts-022 (`ReplayGap`) — all of which were resolved by adding focused round-trip tests.
Additionally, the `MxSparseElement.value` field is typed `MxValue` (the full value union), which means a client could legally set it to another `sparse_array_value = 19` arm, creating a recursive sparse structure. The `// scalar` comment documents the intent, but no test pins that a well-formed sparse element carries only a scalar kind (not `array_value`, `raw_value`, or another `sparse_array_value`). The gateway rejects recursive nesting at validation time, but the contract-level test would document the constraint explicitly.
**Recommendation:** Add round-trip / descriptor-pin tests to `ProtobufContractRoundTripTests`: (a) pin `MxValue.SparseArrayValueFieldNumber == 19` via the generated constant; (b) round-trip an `MxSparseArray` with `element_data_type`, `total_length`, and at least one `MxSparseElement` (covering `index` and a scalar `value`), embedded in an `MxValue` with `KindCase == SparseArrayValue`; (c) assert the `MxSparseArray` field numbers by name via `MxSparseArray.Descriptor.Fields` (1 = `element_data_type`, 2 = `total_length`, 3 = `elements`) and `MxSparseElement.Descriptor.Fields` (1 = `index`, 2 = `value`). Optionally add a second test with an empty `elements` list (valid all-defaults case) to pin that zero elements is not a proto-level error.
**Resolution:** _(2026-06-18)_ Confirmed all three gaps against the proto and generated constants. Added `ProtobufContractRoundTripTests.MxValue_RoundTripsSparseArrayValueAndPinsFieldNumbers` to `ProtobufContractRoundTripTests.cs`. The test: (a) pins `MxValue.SparseArrayValueFieldNumber == 19` via the generated constant; (b) pins all five field numbers by name + number via the descriptor (`MxSparseArray` fields 1/2/3 and `MxSparseElement` fields 1/2); (c) round-trips an `MxValue` with `KindCase == SparseArrayValue` carrying a populated `MxSparseArray` (one `MxSparseElement` with a scalar float value at index 2); (d) verifies an all-defaults `MxSparseArray` with no elements is not a proto-level error. The full `ProtobufContractRoundTrip|GatewayContractInfo` filter is 54/54 green.
### Contracts-024
| Field | Value |
|---|---|
| Severity | Low |
| Category | Documentation & comments |
| Location | `docs/Contracts.md:9-11` |
| Status | Resolved |
**Description:** `docs/Contracts.md` lists `MxValue`, `MxArray`, and `MxStatusProxy` as the types defined in `mxaccess_gateway.proto`, and documents both bulk subscription and bulk write/read command families in detail. The new `MxSparseArray` value arm (`sparse_array_value = 19`) — a public-facing addition to the `MxValue` oneof that changes the write API available to every command variant — is not mentioned anywhere in `docs/Contracts.md`. The CLAUDE.md rule "Update docs in the same change as the source. When public APIs, contracts, configuration … change, the affected docs … must change in the same commit" was not satisfied for this addition; `docs/Contracts.md` now undercounts the public `MxValue` surface. `gateway.md` and `docs/WorkerConversion.md` were updated, but `docs/Contracts.md` — the canonical contracts document linked from the client generation doc — was not.
**Recommendation:** Extend `docs/Contracts.md` to describe `MxSparseArray`: the write-only `sparse_array_value = 19` arm on `MxValue`, the two messages (`MxSparseArray` with `element_data_type`, `total_length`, `elements`; `MxSparseElement` with `index`, `value`), the default-fill-not-preserve semantics for unmentioned indices, and the fact that it is accepted by every write variant (`Write`, `Write2`, `WriteSecured`, `WriteSecured2`, and each `*BulkEntry` entry) but rejected on read/event paths. Cross-reference `gateway.md` for the validation rules and expansion details rather than restating them.
**Resolution:** _(2026-06-18)_ Confirmed `docs/Contracts.md` had no mention of `MxSparseArray` / `MxSparseElement` / `sparse_array_value = 19`. Added a new paragraph in the "Files" section immediately after the `mxaccess_gateway.proto` intro sentence (before the bulk-subscription commands section): names `MxSparseArray` alongside `MxValue`, `MxArray`, and `MxStatusProxy` in the intro line; explains that `sparse_array_value = 19` is the `MxValue.kind` oneof arm for write-only partial-array writes; documents both messages with their fields and field numbers; states the default-fill-not-preserve semantics; and enumerates every write variant that accepts it plus the read/event rejection. Cross-references `gateway.md` for expansion rules and validation constraints.
### Contracts-025
| Field | Value |
|---|---|
| Severity | Low |
| Category | Documentation & comments |
| Location | `src/ZB.MOM.WW.MxGateway.Tests/Contracts/GatewayContractInfoTests.cs:14-25` |
| Status | Resolved |
**Description:** The XML summary on `GatewayContractInfoTests.GatewayProtocolVersion_IsVersionThree` (updated under Contracts-013 resolution to enumerate the alarm and bulk write/read extensions shipped under version 3) does not mention the new `MxSparseArray` / `sparse_array_value = 19` addition, which is also a strictly additive contract change shipped under version 3 without a bump. A reader checking whether a new additive contract feature requires a `GatewayProtocolVersion` bump will look at this test for precedent; finding only the alarm and bulk write/read examples, they cannot tell whether the sparse array addition was also additive-under-3 or was simply omitted by mistake. This is the same class of stale-summary issue as Contracts-013 (which noted the bulk write/read extension was not mentioned after the alarm-only summary).
**Recommendation:** Extend the XML summary to list the `MxSparseArray` write ergonomics extension (`MxSparseArray` / `MxSparseElement` + `sparse_array_value = 19` on `MxValue`, plus the suffix-normalization behavior) alongside the alarm and bulk write/read extensions as a third example of a strictly additive change that shipped under version 3 without a bump. Comment-only change; no test logic or version constant changes.
**Resolution:** _(2026-06-18)_ Confirmed the XML summary on `GatewayProtocolVersion_IsVersionThree` enumerated only the alarm and bulk write/read extensions; the sparse-array addition was missing. Extended the summary to list all three additive-under-version-3 extensions as an ordered enumeration: (1) alarm proto extension; (2) bulk write/read command family; (3) sparse-array write ergonomics (`MxSparseArray` / `MxSparseElement` messages plus `sparse_array_value = 19` on the `MxValue` oneof). Comment-only change; test logic and version constant are unchanged. The full `ProtobufContractRoundTrip|GatewayContractInfo` filter is 54/54 green.
+28 -2
View File
@@ -4,8 +4,8 @@
|---|---|
| Module | `src/ZB.MOM.WW.MxGateway.IntegrationTests` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
@@ -152,6 +152,32 @@ Re-review of the live-test delta: two new `[LiveMxAccessFact]` smoke tests (B8 n
| 9 | Testing coverage | IntegrationTests-032, IntegrationTests-033 |
| 10 | Documentation & comments | IntegrationTests-030, IntegrationTests-031 |
### 2026-06-18 re-review (commit `88915c3`)
Scope: `git diff 8df5ab3..88915c3 -- src/ZB.MOM.WW.MxGateway.IntegrationTests/`. One
commit touched the module: `6b5fe6a` ("fix: resolve code-review findings (locally
verified)"). The IntegrationTests delta is exactly two hunks in
`WorkerLiveMxAccessSmokeTests.cs`: (1) a comment reword on the Suspend/Activate block
(IntegrationTests-031 resolution: "against the advised item" → "against the
added-but-not-advised item (no Advise was issued between AddItem and this call)"); (2)
`catch (TimeoutException)` widened to `catch (TimeoutException ex)` and
`output.WriteLine($"B8: sample-bearing batch predicate timed out: {ex.Message}")` added
before nulling `bufferedBatch` (IntegrationTests-032 resolution). Both are pure
comment/diagnostic fixes with no assertion or logic changes. All ten categories clean.
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | No issues found. Both hunks are comment/diagnostic-only; no assertions, conditions, or API calls changed. |
| 2 | mxaccessgw conventions | No issues found. Tests remain correctly gated behind `[LiveMxAccessFact]`; no secrets logged; no synthesized events; no direct COM instantiation introduced. |
| 3 | Concurrency & thread safety | No issues found. No concurrency-relevant code changed. |
| 4 | Error handling & resilience | No issues found. The `TimeoutException` catch remains non-rethrowing; adding `ex` capture and a `WriteLine` does not affect the error path. |
| 5 | Security | No issues found. `ex.Message` from `WaitForMessageAsync`'s `TimeoutException` carries only a scan count and timeout duration — no credential data. |
| 6 | Performance & resource management | No issues found. No new allocations on non-timeout paths; the exception reference capture on the timeout path is negligible. |
| 7 | Design-document adherence | No issues found. `docs/GatewayTesting.md` was already updated in the same `6b5fe6a` wave (IntegrationTests-030); these two comment fixes require no further doc change. |
| 8 | Code organization & conventions | No issues found. Comment style is consistent with the surrounding block; no namespace or layout changes. |
| 9 | Testing coverage | No issues found. No assertions changed; the `output.WriteLine` adds residual diagnostics only. IntegrationTests-033 remains Deferred (AddItem2/Write2 live parity requires the live rig). |
| 10 | Documentation & comments | No issues found. Both hunks are the documentation fix — the reworded comment now accurately reflects that no `Advise` precedes Suspend/Activate, and the timeout log now surfaces the `WaitForMessageAsync` detail to distinguish the two residual failure modes. |
## Findings
### IntegrationTests-001
+27 -10
View File
@@ -10,17 +10,17 @@ Each module's `findings.md` is the source of truth; this file is generated from
| Module | Reviewer | Date | Commit | Status | Open | Total |
|---|---|---|---|---|---|---|
| [Client.Dotnet](Client.Dotnet/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 29 |
| [Client.Go](Client.Go/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 34 |
| [Client.Java](Client.Java/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 48 |
| [Client.Python](Client.Python/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 36 |
| [Client.Rust](Client.Rust/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 38 |
| [Contracts](Contracts/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 22 |
| [IntegrationTests](IntegrationTests/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 33 |
| [Server](Server/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 56 |
| [Tests](Tests/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 39 |
| [Client.Dotnet](Client.Dotnet/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 30 |
| [Client.Go](Client.Go/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 37 |
| [Client.Java](Client.Java/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 51 |
| [Client.Python](Client.Python/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 38 |
| [Client.Rust](Client.Rust/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 40 |
| [Contracts](Contracts/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 25 |
| [IntegrationTests](IntegrationTests/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 33 |
| [Server](Server/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 58 |
| [Tests](Tests/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 40 |
| [Worker](Worker/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 28 |
| [Worker.Tests](Worker.Tests/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 36 |
| [Worker.Tests](Worker.Tests/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 36 |
## Pending findings
@@ -67,6 +67,7 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Client.Dotnet-018 | Medium | Resolved | Documentation & comments | `clients/dotnet/README.md:137-138` |
| Client.Dotnet-022 | Medium | Resolved | mxaccessgw conventions | `clients/dotnet/Directory.Build.props:1-21` |
| Client.Dotnet-028 | Medium | Resolved | Security | `clients/dotnet/.../MxGatewayClientCli.cs:156` |
| Client.Dotnet-030 | Medium | Resolved | Correctness & logic bugs | `clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs:91-93,113,2023-2050` |
| Client.Go-002 | Medium | Resolved | Error handling & resilience | `clients/go/mxgateway/session.go:440-516` |
| Client.Go-003 | Medium | Resolved | Correctness & logic bugs | `clients/go/cmd/mxgw-go/main.go:517-532` |
| Client.Go-022 | Medium | Resolved | Code organization & conventions | `clients/go/cmd/mxgw-go/main.go:398-412,417-519` |
@@ -131,6 +132,7 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Server-051 | Medium | Resolved | Error handling & resilience | `src/ZB.MOM.WW.MxGateway.Server/Alarms/AlarmWatchListResolver.cs:64-78` |
| Server-054 | Medium | Resolved | Design-document adherence | `docs/DesignDecisions.md` (Session Reconnect / Event Subscribers / Later Revisit Items §470-471), `CLAUDE.md` (Repository-Specific Conventions) |
| Server-056 | Medium | Resolved | Concurrency & thread safety | `src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs:296-310,449-453,629-635` |
| Server-057 | Medium | Resolved | Correctness & logic bugs | `src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs:976-1000` (`NormalizeOutboundCommand`), `:1085-1095` (`MapCommand` tracking), `gateway.md` (array-write ergonomics section), `clients/*/README.md` |
| Tests-003 | Medium | Resolved | Performance & resource management | `src/MxGateway.Tests/Security/Authentication/SqliteAuthStoreTests.cs:170-176`, `src/MxGateway.Tests/Security/Authentication/ApiKeyAdminCliRunnerTests.cs:252-258` |
| Tests-004 | Medium | Resolved | Testing coverage | `src/MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs` |
| Tests-005 | Medium | Resolved | Testing coverage | `src/MxGateway.Tests/Gateway/Grpc/EventStreamServiceTests.cs:239-261`, `src/MxGateway.Tests/Gateway/Sessions/SessionManagerTests.cs` |
@@ -209,6 +211,9 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Client.Go-032 | Low | Resolved | Code organization & conventions | `clients/go/cmd/mxgw-go/main.go:839-841` |
| Client.Go-033 | Low | Resolved | Testing coverage | `clients/go/cmd/mxgw-go/main_test.go` |
| Client.Go-034 | Low | Resolved | Documentation & comments | `clients/go/README.md:245-263` |
| Client.Go-035 | Low | Resolved | Code organization & conventions | `clients/go/cmd/mxgw-go/main.go:1298`, `clients/go/README.md:328-355` |
| Client.Go-036 | Low | Resolved | Testing coverage | `clients/go/cmd/mxgw-go/main_test.go`, `clients/go/cmd/mxgw-go/main.go:364-399` |
| Client.Go-037 | Low | Resolved | Documentation & comments | `clients/go/README.md:136-137` |
| Client.Java-006 | Low | Resolved | Performance & resource management | `clients/java/mxgateway-client/src/main/java/com/dohertylan/mxgateway/client/MxGatewayClient.java:323-328`, `clients/java/mxgateway-client/src/main/java/com/dohertylan/mxgateway/client/GalaxyRepositoryClient.java:279-284` |
| Client.Java-007 | Low | Resolved | Testing coverage | `clients/java/mxgateway-client/src/test/java/com/dohertylan/mxgateway/client/` |
| Client.Java-008 | Low | Resolved | Error handling & resilience | `clients/java/mxgateway-client/src/main/java/com/dohertylan/mxgateway/client/MxGatewayClient.java:298-304` |
@@ -240,6 +245,9 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Client.Java-046 | Low | Resolved | Testing coverage | `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java:680-696` |
| Client.Java-047 | Low | Resolved | Documentation & comments | `clients/java/README.md` |
| Client.Java-048 | Low | Resolved | Documentation & comments | `clients/java/zb-mom-ww-mxgateway-cli/src/main/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCli.java:88-105` |
| Client.Java-049 | Low | Resolved | Code organization & conventions | `clients/java/build.gradle:16`, `clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientVersion.java:12`, `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java:59,89`, `clients/java/README.md:399` |
| Client.Java-050 | Low | Resolved | Testing coverage | `clients/java/zb-mom-ww-mxgateway-cli/src/main/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCli.java:1046-1068` (new `AdviseSupervisoryCommand`), `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java:1306-1313` (stub) |
| Client.Java-051 | Low | Resolved | Documentation & comments | `clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java:622-657` |
| Client.Python-001 | Low | Resolved | Documentation & comments | `clients/python/pyproject.toml:8,25`, `clients/python/src/mxgateway_cli/commands.py:25` |
| Client.Python-002 | Low | Resolved | Code organization & conventions | `clients/python/src/mxgateway/__init__.py:27` |
| Client.Python-004 | Low | Resolved | Correctness & logic bugs | `clients/python/src/mxgateway_cli/commands.py:386,402-404` |
@@ -265,6 +273,8 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Client.Python-033 | Low | Resolved | Correctness & logic bugs | `clients/python/src/zb_mom_ww_mxgateway_cli/commands.py:772,1490-1494` |
| Client.Python-034 | Low | Resolved | Correctness & logic bugs | `clients/python/src/zb_mom_ww_mxgateway_cli/commands.py:1497-1501` |
| Client.Python-035 | Low | Resolved | Code organization & conventions | `clients/python/src/zb_mom_ww_mxgateway/__init__.py`, `.../options.py:63-77`, `.../galaxy.py:293` |
| Client.Python-037 | Low | Resolved | Correctness & logic bugs | `clients/python/pyproject.toml:10` |
| Client.Python-038 | Low | Resolved | Testing coverage | `clients/python/tests/`, `clients/python/src/zb_mom_ww_mxgateway_cli/commands.py:280-299,742-758` |
| Client.Rust-004 | Low | Resolved | Documentation & comments | `clients/rust/src/version.rs:7` |
| Client.Rust-007 | Low | Resolved | Design-document adherence | `clients/rust/RustClientDesign.md:14-55` |
| Client.Rust-008 | Low | Resolved | Performance & resource management | `clients/rust/src/value.rs:161-261` |
@@ -287,6 +297,8 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Client.Rust-036 | Low | Resolved | Design-document adherence | `clients/rust/RustClientDesign.md:351` |
| Client.Rust-037 | Low | Resolved | Design-document adherence | `clients/rust/README.md:164-179` |
| Client.Rust-038 | Low | Resolved | Testing coverage | `clients/rust/crates/mxgw-cli/src/main.rs:2336-2564` |
| Client.Rust-039 | Low | Resolved | Design-document adherence | `clients/rust/RustClientDesign.md:101-131` (Session API block); `clients/rust/RustClientDesign.md:326-353` (CLI commands table) |
| Client.Rust-040 | Low | Resolved | Testing coverage | `clients/rust/tests/client_behavior.rs:1195-1224` (`sparse_int32_value` helper); `clients/rust/tests/client_behavior.rs:1226-1264` (unit tests using the helper) |
| Contracts-001 | Low | Resolved | Design-document adherence | `docs/Grpc.md:13` (and `:3`, `:32`, `:39`) |
| Contracts-003 | Low | Won't Fix | Code organization & conventions | `src/MxGateway.Contracts/MxGateway.Contracts.csproj:10` |
| Contracts-004 | Low | Resolved | Documentation & comments | `src/MxGateway.Contracts/GatewayContractInfo.cs:3-6` |
@@ -307,6 +319,9 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Contracts-020 | Low | Resolved | Design-document adherence | `gateway.md:1087,1101-1102` |
| Contracts-021 | Low | Resolved | Documentation & comments | `src/ZB.MOM.WW.MxGateway.Contracts/Protos/mxaccess_gateway.proto:731-733` |
| Contracts-022 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Contracts/ProtobufContractRoundTripTests.cs` |
| Contracts-023 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Contracts/ProtobufContractRoundTripTests.cs` |
| Contracts-024 | Low | Resolved | Documentation & comments | `docs/Contracts.md:9-11` |
| Contracts-025 | Low | Resolved | Documentation & comments | `src/ZB.MOM.WW.MxGateway.Tests/Contracts/GatewayContractInfoTests.cs:14-25` |
| IntegrationTests-007 | Low | Resolved | Concurrency & thread safety | `src/MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs:20`, `src/MxGateway.IntegrationTests/Galaxy/GalaxyRepositoryLiveTests.cs:5`, `src/MxGateway.IntegrationTests/DashboardLdapLiveTests.cs:9` |
| IntegrationTests-008 | Low | Resolved | Code organization & conventions | `src/MxGateway.IntegrationTests/LiveLdapFactAttribute.cs`, `src/MxGateway.IntegrationTests/Galaxy/LiveGalaxyRepositoryFactAttribute.cs`, `src/MxGateway.IntegrationTests/LiveMxAccessFactAttribute.cs` |
| IntegrationTests-009 | Low | Resolved | Documentation & comments | `src/MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs:372-375` |
@@ -366,6 +381,7 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Server-052 | Low | Resolved | Documentation & comments | `src/ZB.MOM.WW.MxGateway.Server/Alarms/IAlarmWatchListResolver.cs:24-30`, `src/ZB.MOM.WW.MxGateway.Server/Alarms/AlarmWatchListResolver.cs:101-114`, `docs/GatewayConfiguration.md:247` |
| Server-053 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Alarms/AlarmWatchListResolverTests.cs`, `src/ZB.MOM.WW.MxGateway.Tests/Alarms/GatewayAlarmMonitorProviderModeTests.cs` |
| Server-055 | Low | Resolved | Correctness & logic bugs | `src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs:842-851,1841-1871` |
| Server-058 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ConstraintEnforcerTests.cs` |
| Tests-007 | Low | Resolved | Code organization & conventions | `src/MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceTests.cs:682`, `src/MxGateway.Tests/Gateway/Grpc/GalaxyRepositoryGrpcServiceTests.cs:324`, `src/MxGateway.Tests/Gateway/GatewayEndToEndFakeWorkerSmokeTests.cs:460`, `src/MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs:233` |
| Tests-008 | Low | Resolved | mxaccessgw conventions | `src/MxGateway.Tests/Gateway/Sessions/WorkerAlarmRpcDispatcherTests.cs:1-9`, `src/MxGateway.Tests/Gateway/Sessions/NotWiredAlarmRpcDispatcherTests.cs:1-3`, `src/MxGateway.Tests/Gateway/Sessions/SessionManagerAlarmAutoSubscribeTests.cs:1` |
| Tests-009 | Low | Resolved | Documentation & comments | `src/MxGateway.Tests/Gateway/Sessions/SessionManagerTests.cs:36-37,99,365` |
@@ -393,6 +409,7 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Tests-037 | Low | Won't Fix | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Contracts/ProtobufContractRoundTripTests.cs` |
| Tests-038 | Low | Resolved | Performance & resource management | `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionEventDistributorTests.cs:702-713` |
| Tests-039 | Low | Resolved | Concurrency & thread safety | `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewaySessionDashboardMirrorTests.cs` (`DashboardMirror_AndGrpcSubscriber_BothReceiveEvents`) |
| Tests-040 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs` |
| Worker-009 | Low | Resolved | Performance & resource management | `src/MxGateway.Worker/Ipc/WorkerFrameReader.cs:31,49`, `src/MxGateway.Worker/Ipc/WorkerFrameWriter.cs:57-58` |
| Worker-010 | Low | Resolved | Correctness & logic bugs | `src/MxGateway.Worker/Conversion/VariantConverter.cs:204-226` |
| Worker-011 | Low | Resolved | Correctness & logic bugs | `src/MxGateway.Worker/Ipc/WorkerPipeClient.cs:169-171` |
+49 -2
View File
@@ -4,8 +4,8 @@
|---|---|
| Module | `src/ZB.MOM.WW.MxGateway.Server` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
@@ -69,6 +69,23 @@ findings (Server-001 through Server-032) are unchanged by this pass.
| 9 | Testing coverage | Issues found: Server-037 (no test for the corrupt-snapshot restore path or for `PersistSnapshot = false` at the cache level). |
| 10 | Documentation & comments | No issues found — XML docs match behavior; the `GalaxyRepository.md` "On-disk snapshot" section documents the Stale-on-restore lifecycle. |
### 2026-06-18 review (commit 88915c3)
Re-review of the array-write-ergonomics feature (`git diff 8df5ab3..88915c3 -- src/ZB.MOM.WW.MxGateway.Server/`): the new `SparseArrayExpander` and `ArrayAddressNormalizer`, the `NormalizeOutboundCommand` choke point in `GatewaySession.InvokeAsync`, the re-normalize at the `TrackCommandReply`/`MapCommand` tracking call sites, and the `ConstraintEnforcer.ResolveTarget` `[]`-suffix fallback. The range also lands the already-filed Server-055 (`_everHadEventSubscriber` detach-grace gate) and Server-056 (`SessionEventDistributor._completed` late-registrant guard) resolutions; both were re-verified sound here and remain closed. Security focus — the authorization `[]` fallback: it changes only *which* Galaxy metadata record resolves (turning a spurious `tag_metadata` deny into a real scope/classification decision), stays `IsArray`-gated, and the scope check (`MatchesPathOrTag` on `ContainedPath` + the original bare `tagAddress`) still runs unchanged, so a scoped key cannot reach a non-array tag or an out-of-scope array. The authz check (bare address) and the worker bind (suffixed via the same `IsArray`-gated probe) resolve the identical attribute — no check-vs-bind mismatch. Worker untouched; parity preserved (single whole-array COM write). Two new findings.
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | Issues found: Server-057 (`NormalizeOutboundCommand`/`MapCommand` normalize only single `AddItem`/`AddItem2`; bare array addresses added via `AddItemBulk`/`AddBufferedItem` register non-write-capable handles). SparseArrayExpander verified sound: total_length=0 / oversize / out-of-range / duplicate / kind-mismatch all → `InvalidArgument`; `Array.MaxLength` guard precedes the `(int)` cast; Int32-vs-Int64 selection mirrors the worker converter; expansion targets `Value` not `timestamp_value` across all 8 write variants. |
| 2 | mxaccessgw conventions | No issues found — file-scoped namespaces, `sealed`/`internal static`, `Async` suffixes, primary constructors, MXAccess-aligned naming; worker still does an honest whole-array COM write; no UI libraries; no value/secret logging added (write payloads never logged). |
| 3 | Concurrency & thread safety | No issues found — `NormalizeOutboundCommand` mutates the `WorkerCommand.Command` deep-clone produced by `MapCommand` (`request.Command.Clone()`), never the client's `MxCommand`, and the tracking path re-normalizes its own separate copy; `ArrayAddressNormalizer`/`SparseArrayExpander` are stateless (read the cache snapshot per call); `_everHadEventSubscriber` and the `SessionEventDistributor._completed` guard serialize correctly under their locks. |
| 4 | Error handling & resilience | No issues found — invalid sparse payloads surface as `RpcException(InvalidArgument)` and propagate uncaught (correct client-facing error); the normalizer never throws and passes through when metadata is cold. |
| 5 | Security | No issues found — the `ConstraintEnforcer` `[]` fallback is `IsArray`-gated, does not widen scope (scope/classification checks unchanged), and resolves the same attribute the worker binds; covered by `CheckReadTagAsync_WithBareArrayName_*` and the missing-non-array negative test. |
| 6 | Performance & resource management | No issues found — expander allocates one array of `total_length` slots (inherent to a whole-array write) and the work is O(length + elements); the normalizer is a single dictionary probe per AddItem. |
| 7 | Design-document adherence | No issues found — worker untouched, single whole-array COM write preserved; `gateway.md`, `docs/WorkerConversion.md`, `docs/DesignDecisions.md`, and all five client READMEs were updated in the same commit and match the code (sparse semantics, default-fill reset, `[]` normalization). |
| 8 | Code organization & conventions | No issues found — new types live under `Sessions/`, registered as a singleton in `AddGatewaySessions` consistent with `IGalaxyHierarchyCache`; the optional `addressNormalizer` ctor parameter keeps legacy unit-construction paths working. |
| 9 | Testing coverage | Issues found: Server-058 (no test asserts a bare-array name that resolves via the `[]` fallback is still *denied* when out of scope, and `CheckWriteHandleAsync` array-via-suffixed-registration / classification is untested). Otherwise strong: `SparseArrayExpanderTests` (210 lines), `ArrayAddressNormalizerTests` (105), and the two `ConstraintEnforcerTests` cases. |
| 10 | Documentation & comments | No issues found — XML docs and inline comments on the new types are accurate (the GatewaySession comment correctly notes `MapCommand` deep-clones, contradicting the plan's stale "same instance" note); the `AddItemBulk` gap is documentation-adjacent and is captured under Server-057. |
### 2026-06-16 re-review (commit 8df5ab3)
Re-review of the session-resilience epic + §8 delta (`git diff 410acc9..8df5ab3`): `SessionEventDistributor` multi-subscriber fan-out, replay-on-reconnect, detach-grace retention, bounded worker-ready wait, dashboard auto-login.
@@ -1084,3 +1101,33 @@ Additionally, `GatewayAlarmMonitor.ApplyProviderModeChangeAsync` increments the
**Recommendation:** Record terminal completion (a `_completed` flag plus the terminal error) under `_lifecycleLock` and have both register paths complete a late registrant's channel immediately with the same terminal state.
**Resolution:** 2026-06-17: added `_completed` + `_completionError`, set inside `CompleteAllSubscribers` under `_lifecycleLock` — the same lock the register paths take, so completion and registration serialize (a subscriber added before the sweep is completed by the loop; one racing in after sees `_completed` and self-completes). `Register` and `RegisterWithReplay` now `TryComplete` a late registrant's channel with `_completionError` when `_completed`; a late resume still receives its retained replay batch, then a cleanly-completed empty live channel. No lock-ordering risk — `CompleteAllSubscribers` takes only `_lifecycleLock`, and the subscriber channels use `AllowSynchronousContinuations=false` so `TryComplete` under the lock runs no continuation inline. New regression `[Fact]` `Register_AfterSourceCompletes_CompletesLateSubscriberInsteadOfHanging` (`SessionEventDistributorTests.cs`) registers a subscriber after the pump completes and asserts its channel completes (bounded read); verified it fails without the fix (5 s timeout) and passes with it (12 ms). The racy `GatewaySessionDashboardMirrorTests.DashboardMirror_AndGrpcSubscriber_BothReceiveEvents` that exposed it was also made deterministic — see Tests-039.
### Server-057
| Field | Value |
|---|---|
| Severity | Medium |
| Category | Correctness & logic bugs |
| Location | `src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs:976-1000` (`NormalizeOutboundCommand`), `:1085-1095` (`MapCommand` tracking), `gateway.md` (array-write ergonomics section), `clients/*/README.md` |
| Status | Resolved |
**Description:** The array-suffix `[]` normalization runs only for the single-add commands `AddItem` and `AddItem2` — `NormalizeOutboundCommand` has no case for `AddItemBulk` (or `AddBufferedItem`), and the `MapCommand` tracking switch likewise normalizes only the `AddItem`/`AddItem2` arms (`AddItemBulk` flows through `TrackBulkItems`/`AddBufferedItem` with the raw address). MXAccess requires the `[]` suffix on the AddItem address for an array attribute to register a *write-capable* handle. A client that registers a bare array address via `AddItemBulk` therefore binds a non-write-capable handle, and a later `Write`/`WriteSecured`/sparse write against that handle silently lands on a read-only-ish handle — the exact failure mode this feature fixes for the single-add path. The behavior is inconsistent across the add family, and `gateway.md` / the client READMEs describe normalization as happening "at AddItem time" and explicitly carve out only `ReadBulk`, giving no signal that `AddItemBulk` is excluded. `AddBufferedItem` is lower-risk (buffered/historical read items are not normally written) but is the same gap.
**Recommendation:** Either (a) extend `NormalizeOutboundCommand` and the `MapCommand` tracking path to normalize each `AddItemBulk.TagAddresses` entry (and `AddBufferedItem.ItemDefinition`) the same `IsArray`-gated way, keeping the constraint check, the worker bind, and the stored `SessionItemRegistration.TagAddress` consistent; or (b) if bulk-add normalization is intentionally out of scope for this feature, state that explicitly in `gateway.md` and the client READMEs (alongside the existing `ReadBulk` carve-out) so clients know bulk-added array handles must carry the `[]` suffix themselves to be writable.
**Resolution:** 2026-06-18 — Took option (a). Root cause confirmed: `NormalizeOutboundCommand` had no `AddItemBulk`/`AddBufferedItem` case, so the worker bound bare (non-write-capable) array handles for those paths while single-add was already fixed. Added `AddItemBulk` (normalizes each `TagAddresses` entry in place) and `AddBufferedItem` (normalizes `ItemDefinition`) cases to `NormalizeOutboundCommand`; added the matching `AddBufferedItem` normalization to the `TrackCommandReply`/`MapCommand` tracking path (its registration keys off the command's `ItemDefinition`). `AddItemBulk` tracking needs no change — the worker echoes the already-suffixed address back in each `SubscribeResult.TagAddress`, which `TrackBulkItems` stores. Authz is unchanged and consistent: `FilterTagBulkAsync` checks the bare address through `ConstraintEnforcer.ResolveTarget`'s `[]` fallback, mirroring single-add. Updated `gateway.md` and all five client READMEs (dotnet/go/python/rust/java) so the add-family normalization no longer reads as AddItem-only; the `ReadBulk` carve-out stays. Regression tests: `GatewayArrayWriteWiringTests.AddItemBulk_BareArrayAddress_NormalizedOnWireAndInRegistration`, `.AddBufferedItem_BareArrayAddress_NormalizedOnWireAndInRegistration`.
### Server-058
| Field | Value |
|---|---|
| Severity | Low |
| Category | Testing coverage |
| Location | `src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ConstraintEnforcerTests.cs` |
| Status | Resolved |
**Description:** The new `ConstraintEnforcer.ResolveTarget` `[]`-suffix fallback is security-sensitive: it turns a bare-array address that previously missed the Galaxy index (→ spurious `tag_metadata` deny) into a real scope/classification decision. The added tests cover the in-scope-allow case (`CheckReadTagAsync_WithBareArrayName_ResolvesViaArraySuffixFallback`) and the missing/non-array negative case (`CheckReadTagAsync_WithMissingNonArrayName_StillFailsToResolve`), but **no test asserts that a bare-array name which now resolves via the fallback is still denied when it is out of the key's read/write scope** — i.e. that the fallback widened resolution but not authorization. There is also no `CheckWriteHandleAsync` test exercising an array handle whose `SessionItemRegistration.TagAddress` is the suffixed form (`Obj.Arr[]`) resolving directly through `ResolveTarget` for the write-scope and `MaxWriteClassification` checks. These are the precise paths a regression could silently widen.
**Recommendation:** Add a `CheckReadTagAsync` (and a `CheckWriteHandleAsync`) case where the bare/suffixed array attribute resolves but the configured `ReadTagGlobs`/`WriteSubtrees` exclude it, asserting a `read_scope`/`write_scope` `ConstraintFailure` is still returned; and a `CheckWriteHandleAsync` case asserting `MaxWriteClassification` is enforced against the array attribute's `SecurityClassification` via the suffixed registration address.
**Resolution:** 2026-06-18 — Added three `ConstraintEnforcerTests` cases (the test fixture gained a second array attribute `Pump_001.Setpoints[]` with `SecurityClassification = 2` to exercise the classification path): `CheckReadTagAsync_WithBareArrayName_OutOfScope_StillDeniedReadScope` (bare array resolves via the `[]` fallback but is denied `read_scope` when out of `ReadTagGlobs` — guards that the fallback widened resolution, not authorization), `CheckWriteHandleAsync_WithSuffixedArrayRegistration_OutOfScope_StillDeniedWriteScope` (an array handle whose registration `TagAddress` is the suffixed `Pump_001.Levels[]` resolves through `ResolveTarget` and is denied `write_scope`), and `CheckWriteHandleAsync_WithSuffixedArrayRegistration_ClassificationTooHigh_StillDenied` (in-scope suffixed array handle denied `max_write_classification` when the attribute's `SecurityClassification` exceeds `MaxWriteClassification`). Tests-only change; no production code touched.
+34 -2
View File
@@ -4,8 +4,8 @@
|---|---|
| Module | `src/ZB.MOM.WW.MxGateway.Tests` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
@@ -111,6 +111,23 @@ fakes in two test files.
| 9 | Testing coverage | Issues found: Tests-026 (no test proves `EventStreamService` actually calls `IDashboardEventBroadcaster.Publish` for each event — the only consumers in tests are `Null` fakes). |
| 10 | Documentation & comments | No issues found in this diff. |
### 2026-06-18 re-review (commit `88915c3`)
Re-review of the `8df5ab3..88915c3` diff. New files: `SparseArrayExpanderTests.cs`, `ArrayAddressNormalizerTests.cs`, `GatewayArrayWriteWiringTests.cs` (array-write feature tests); additions to `ConstraintEnforcerTests.cs` (bare-array-name authz fallback), `ProtobufContractRoundTripTests.cs` (ReplayGap round-trip), `GatewaySessionTests.cs` (failed-first-attach regression), `SessionEventDistributorTests.cs` (register-after-completion + DrainUntilFaultAsync fix), `GatewaySessionDashboardMirrorTests.cs` (Tests-039 release-gate fix), `GatewayOptionsValidatorTests.cs` (DetachGraceSeconds / ReplayBuffer bounds).
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | No issues found. All new tests assert the correct post-condition; `AddItem_BareArrayAddress_NormalizedOnWireAndInRegistration` correctly verifies re-normalization in `TrackCommandReply` via a bare-address `trackingCopy`; `DrainUntilFaultAsync` graceful-completion guard is correct. |
| 2 | mxaccessgw conventions | No issues found. All new files use file-scoped namespaces, sealed classes, target-typed `new()`, PascalCase `Method_Condition_Result` names, and explicit types. |
| 3 | Concurrency & thread safety | No issues found. `Register_AfterSourceCompletes_CompletesLateSubscriberInsteadOfHanging` correctly proves pump-completed ordering via early-subscriber drain before registering the late subscriber. The Tests-039 release-gate uses `TaskCompletionSource(RunContinuationsAsynchronously)` and `ActiveEventSubscriberCount == 1` gating. |
| 4 | Error handling & resilience | No issues found. `SparseArrayExpanderTests` covers all six `RpcException(InvalidArgument)` paths (zero length, oversize length, out-of-range index, duplicate index, unsupported type, element-kind mismatch). |
| 5 | Security | No issues found. The two new `ConstraintEnforcerTests` correctly pin both directions of the `[]` suffix fallback: bare array name resolves (no spurious denial); bare non-array/missing name still fails to resolve (no false positive). |
| 6 | Performance & resource management | No issues found. `GatewayArrayWriteWiringTests.CapturingWorkerClient` implements `IAsyncDisposable` as `ValueTask.CompletedTask`; no unowned resource. `GatewaySessionTests.DetachGrace_FailedFirstAttach_DoesNotEnterGrace` uses `await using`. |
| 7 | Design-document adherence | No issues found. Sparse-expansion and array-suffix normalization tests reflect the CLAUDE.md parity contract ("MXAccess has no partial-array write primitive"); the `ConstraintEnforcer` bare-name fallback tests match the `ArrayAddressNormalizer` contract. |
| 8 | Code organization & conventions | No issues found. The `StubGalaxyHierarchyCache` is duplicated between `ArrayAddressNormalizerTests` and `GatewayArrayWriteWiringTests` (both in the same namespace), but both are `private sealed class` — duplication is confined and the existing Tests-007 / Tests-021 consolidation pattern applies only to test-support types shared across multiple test classes, not private fakes within a single class. Acceptable. |
| 9 | Testing coverage | Issue found: Tests-040 (`GatewayArrayWriteWiringTests` covers `Write` and `WriteBulk` sparse expansion wiring through `GatewaySession.InvokeAsync` but omits the other six write variants — `WriteSecured`, `Write2`, `WriteSecured2`, `Write2Bulk`, `WriteSecuredBulk`, `WriteSecured2Bulk` — each of which has its own `case` arm in `NormalizeOutboundCommand` and could silently regress). |
| 10 | Documentation & comments | No issues found. New files carry accurate class-level `<summary>` docs; test method summaries correctly describe pre/post conditions; the `DrainUntilFaultAsync` comment update precisely describes the new escape hatch. |
#### 2026-06-16 re-review (commit 8df5ab3)
Re-review of the gateway-test delta (session-resilience epic + §8). New tests are high quality (bounded async waits, FakeTimeProvider, deterministic gating, meaningful assertions). Verified the §8 FakeWorkerProcess consolidation did NOT drop the `entireProcessTree` kill assertion. Only Low coverage-gap / one latent helper footgun.
@@ -724,3 +741,18 @@ The cancellation tests for `WorkerClient` in `WorkerClientTests` *do* exercise t
**Recommendation:** Make the test deterministic — hold the worker stream until both the dashboard mirror and the gRPC subscriber have attached, then release, so neither subscriber can miss an event regardless of scheduling.
**Resolution:** 2026-06-17 — added a release-gate to the test's `FakeWorkerClient` (`HoldEventsUntilReleased()` / `ReleaseEvents()`; `ReadEventsAsync` awaits the gate before yielding, ungated by default so other tests are unaffected). The test now holds the stream, starts the gRPC reader on a background task, waits for `session.ActiveEventSubscriberCount == 1` (the internal dashboard mirror is excluded from the count, so this confirms the gRPC subscriber attached), then releases — both subscribers deterministically receive all three events. With the Server-056 production fix in place, the full `GatewaySessionDashboardMirrorTests` class now passes (5/5) instead of hanging.
### Tests-040
| Field | Value |
|---|---|
| Severity | Low |
| Category | Testing coverage |
| Location | `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs` |
| Status | Resolved |
**Description:** `GatewayArrayWriteWiringTests` covers two of eight sparse-write arms in `GatewaySession.NormalizeOutboundCommand`: `Write` (single) and `WriteBulk`. The remaining six arms — `WriteSecured`, `Write2`, `WriteSecured2`, `Write2Bulk`, `WriteSecuredBulk`, `WriteSecured2Bulk` — all call `ExpandValue(entry.Value)` through the same switch, but no wiring test exercises them through `GatewaySession.InvokeAsync`. The class summary says it covers "the single outbound choke point" and that "no sparse value is ever forwarded"; the claim is accurate for the two covered variants but unverified for the other six. A regression accidentally dropping one of the six remaining `case` arms, or shifting a brace so a case falls through to the default (no-op), would pass the entire `GatewayArrayWriteWiringTests` suite.
**Recommendation:** Add one wiring test per uncovered variant (or a single `[Theory]` over the six command kinds), constructing the matching command type with a `SparseArrayValue` and asserting `worker.LastCommand!.Command.<Variant>.Value.KindCase == MxValue.KindOneofCase.ArrayValue` after `session.InvokeAsync`. The `SparseArrayExpanderTests` already pin the expander logic exhaustively; the wiring tests need only check that the choke point invokes expansion for each variant, not the expansion semantics themselves. The four secured variants (`WriteSecured`, `Write2`, `WriteSecured2`, `WriteSecured2Bulk`) can reuse the same `CapturingWorkerClient` stub.
**Resolution:** 2026-06-18 — root cause confirmed: the six arms (`WriteSecured`, `Write2`, `WriteSecured2`, `Write2Bulk`, `WriteSecuredBulk`, `WriteSecured2Bulk`) each had a `case` in `NormalizeOutboundCommand` calling `ExpandValue` but no wiring test. Server-057's additions (`AddItemBulk`, `AddBufferedItem`) covered address-normalization tests only, not the missing write-expansion variants. Added six tests to `GatewayArrayWriteWiringTests.cs` — one per uncovered arm — each constructing the matching command with a 4-element `SparseArrayValue` (Integer, single element set), driving it through `GatewaySession.InvokeAsync`, and asserting `worker.LastCommand.Command.<Variant>.Value.KindCase == ArrayValue` and the expected element positions. Tests: `WriteSecured_SparseArrayValue_ExpandedBeforeReachingWorker`, `Write2_SparseArrayValue_ExpandedBeforeReachingWorker`, `WriteSecured2_SparseArrayValue_ExpandedBeforeReachingWorker`, `Write2Bulk_SparseArrayEntryValue_ExpandedBeforeReachingWorker`, `WriteSecuredBulk_SparseArrayEntryValue_ExpandedBeforeReachingWorker`, `WriteSecured2Bulk_SparseArrayEntryValue_ExpandedBeforeReachingWorker`. All 13 `GatewayArrayWriteWiring` tests pass (7 pre-existing + 6 new).
+29 -2
View File
@@ -4,11 +4,38 @@
|---|---|
| Module | `src/ZB.MOM.WW.MxGateway.Worker.Tests` |
| Reviewer | Claude Code |
| Review date | 2026-06-16 |
| Commit reviewed | `8df5ab3` |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Status | Re-reviewed |
| Open findings | 0 |
## 2026-06-18 re-review (commit `88915c3`)
Re-review of `git diff 8df5ab3..88915c3 -- src/ZB.MOM.WW.MxGateway.Worker.Tests/`. Three files changed, all applying previously-recorded findings rather than introducing new feature logic:
- `WorkerPipeSessionTests.cs` — Worker.Tests-036 fix: removes the redundant wall-clock `elapsed < 5s` assertion from `RunAsync_SendsFirstHeartbeatImmediatelyOnEnteringLoop` and replaces it with an inline comment explaining the omission.
- `MxAccessCommandExecutorTests.cs` — Worker.Tests-035 fix: adds `DispatchAsync_WithUnknownCommandKind_ReturnsInvalidRequestWithUnsupportedDiagnostic`; removes the nested `FakeMxStatus` class (Worker.Tests-034 consolidation).
- `TestSupport/NoopMxAccessServer.cs` — Worker.Tests-034 fix: adds the consolidation remarks block to `FakeMxStatus` explaining it was previously duplicated in `MxAccessCommandExecutorTests`.
The array-write-ergonomics feature (the bulk of commits between `8df5ab3` and `88915c3`) deliberately left the Worker untouched — sparse arrays are expanded gateway-side before reaching the worker IPC boundary — which is consistent with the task brief. No new test code was introduced as part of that feature in this module.
Net48 compatibility check: no `init`-only properties, no positional records, no `IsExternalInit`, no other net48-hostile constructs in the additions.
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | No issues found — the new executor test correctly casts `int.MaxValue` to `MxCommandKind`, dispatches through the real `MxAccessStaSession.DispatchAsync`, and asserts both the status code and the diagnostic substring; the assertion is neither too weak nor tautological. |
| 2 | mxaccessgw conventions | No issues found — test method name follows `Method_Scenario_Expectation`; `NoopMxAccessServer.cs` remarks block cites the correct finding ID; no style drift. |
| 3 | Concurrency & thread safety | No issues found — no new shared mutable state or async patterns introduced; the wall-clock assertion removal in `WorkerPipeSessionTests` is strictly a deletion. |
| 4 | Error handling & resilience | No issues found — the unknown-kind test pins the discard arm returns `InvalidRequest` rather than throwing; no new error paths added. |
| 5 | Security | No issues found — no credentials, secrets, or sensitive data involved. |
| 6 | Performance & resource management | No issues found — no new disposable objects introduced without `using`; `StaRuntime` and `MxAccessStaSession` remain `using`-declared in the new test. |
| 7 | Design-document adherence | No issues found — the executor test correctly exercises the gateway↔worker boundary at the `MxAccessStaSession` level (not raw COM), consistent with `docs/MxAccessWorkerInstanceDesign.md`. |
| 8 | Code organization & conventions | No issues found — `FakeMxStatus` deduplication is complete; the nested class is gone from `MxAccessCommandExecutorTests` and the shared copy's XML doc now explains the consolidation. |
| 9 | Testing coverage | No issues found — Worker.Tests-034/035/036 are the last open items from the prior pass; all three are now closed. No new coverage gaps introduced. |
| 10 | Documentation & comments | No issues found — the inline comment in `WorkerPipeSessionTests` correctly attributes the omission to the Worker.Tests-003/004/013/020 pattern; the `FakeMxStatus` remarks block is accurate. |
**No new findings. All prior open items (Worker.Tests-034, -035, -036) resolved.**
## 2026-06-15 re-review (commit `410acc9`)
Re-review of the alarm-fallback test additions in `git diff 42b0037..HEAD --
+18 -1
View File
@@ -8,7 +8,24 @@ recreated by the contracts project build.
`src/ZB.MOM.WW.MxGateway.Contracts/Protos/mxaccess_gateway.proto` defines the public
`MxAccessGateway` gRPC service, command payloads, command replies, event DTOs,
`MxValue`, `MxArray`, and `MxStatusProxy`.
`MxValue`, `MxArray`, `MxSparseArray`, and `MxStatusProxy`.
`MxValue` carries a `kind` oneof with arms for all scalar and array types. One
arm is `sparse_array_value = 19` (field number 19), which carries an
`MxSparseArray`. `MxSparseArray` is a write-only value type: the gateway accepts
it on every write variant (`Write`, `Write2`, `WriteSecured`, `WriteSecured2`,
and the corresponding `*BulkEntry` shapes), expands it into a full,
default-filled `MxArray` before forwarding to the worker, and rejects it on
read or event paths. The worker never receives or produces it.
`MxSparseArray` has three fields: `element_data_type` (1, the `MxDataType` of
every element), `total_length` (2, the length of the expanded full array), and
`elements` (3, `repeated MxSparseElement`). Each `MxSparseElement` has `index`
(1, zero-based position in the expanded array) and `value` (2, a scalar
`MxValue`). Indices not mentioned in `elements` take the element type's default
value — they are reset, not preserved. See `gateway.md` section
"MxSparseArray — default-fill partial array writes" for the expansion rules,
validation constraints, and the scope requirements per write variant.
The public command model includes bulk subscription command kinds for
`AddItemBulk`, `AdviseItemBulk`, `RemoveItemBulk`, `UnAdviseItemBulk`,
+11 -8
View File
@@ -1124,14 +1124,17 @@ Known important parity areas from existing captures:
representation (unmentioned indices → type default) before sending the
whole-array write to the worker.
- Array attribute addresses require the `[]` body suffix to be write-capable.
The gateway normalizes bare-name addresses at `AddItem` time: when Galaxy
metadata confirms `is_array`, the gateway appends `[]` before registering the
handle with the worker. When metadata is unavailable or the address is not
recognized as an array, the address is forwarded unchanged so existing
behavior is not regressed. The normalized address is stored in
`SessionItemRegistration.TagAddress` and applies consistently to all
subsequent writes on that handle. `ReadBulk` is unaffected — it uses raw
address strings with its own ephemeral registration.
The gateway normalizes bare-name addresses at add-item time across the whole
add family — single `AddItem`/`AddItem2`, the batched `AddItemBulk`, and
`AddBufferedItem`: when Galaxy metadata confirms `is_array`, the gateway
appends `[]` before registering the handle with the worker. When metadata is
unavailable or the address is not recognized as an array, the address is
forwarded unchanged so existing behavior is not regressed. The normalized
address is stored in `SessionItemRegistration.TagAddress` (for `AddItemBulk`
the worker echoes the suffixed address it bound back in each
`SubscribeResult.TagAddress`) and applies consistently to all subsequent
writes on that handle. `ReadBulk` is unaffected — it uses raw address strings
with its own ephemeral registration.
The gateway should not "fix" these behaviors unless the client explicitly opts
into a non-parity mode.
@@ -987,6 +987,19 @@ public sealed class GatewaySession
break;
case MxCommand.PayloadOneofCase.AddItem2:
command.AddItem2.ItemDefinition = NormalizeAddress(command.AddItem2.ItemDefinition);
break;
case MxCommand.PayloadOneofCase.AddBufferedItem:
command.AddBufferedItem.ItemDefinition = NormalizeAddress(command.AddBufferedItem.ItemDefinition);
break;
case MxCommand.PayloadOneofCase.AddItemBulk:
// Normalize each bare array address in place so the worker binds a write-capable handle
// for every array tag in the batch (the same IsArray-gated rewrite the single-add path
// applies). Scalar addresses pass through unchanged.
for (int i = 0; i < command.AddItemBulk.TagAddresses.Count; i++)
{
command.AddItemBulk.TagAddresses[i] = NormalizeAddress(command.AddItemBulk.TagAddresses[i]);
}
break;
case MxCommand.PayloadOneofCase.Write:
ExpandValue(command.Write.Value);
@@ -1089,9 +1102,16 @@ public sealed class GatewaySession
TrackItem(command.AddItem2.ServerHandle, reply.AddItem2.ItemHandle, NormalizeAddress(command.AddItem2.ItemDefinition));
break;
case MxCommandKind.AddBufferedItem when reply.AddBufferedItem is not null:
TrackItem(command.AddBufferedItem.ServerHandle, reply.AddBufferedItem.ItemHandle, command.AddBufferedItem.ItemDefinition);
// The reply carries no address, so tracking keys off the command's ItemDefinition;
// re-apply the array-suffix normalization (the tracking copy is a separate, un-mutated
// instance from the one forwarded at the InvokeAsync choke point) so the registration
// matches the write-capable handle the worker bound.
TrackItem(command.AddBufferedItem.ServerHandle, reply.AddBufferedItem.ItemHandle, NormalizeAddress(command.AddBufferedItem.ItemDefinition));
break;
case MxCommandKind.AddItemBulk when reply.AddItemBulk is not null:
// The worker echoes back the (already-normalized) address it bound in each
// SubscribeResult.TagAddress, so TrackBulkItems stores the suffixed array address
// without re-normalizing here.
TrackBulkItems(reply.AddItemBulk);
break;
case MxCommandKind.SubscribeBulk when reply.SubscribeBulk is not null:
@@ -13,15 +13,18 @@ public sealed class GatewayContractInfoTests
/// <summary>
/// Pins the current <see cref="GatewayContractInfo.GatewayProtocolVersion"/>
/// constant at 3. Both the alarm proto extension (`AcknowledgeAlarm` /
/// `QueryActiveAlarms` RPCs, the `OnAlarmTransitionEvent` body, and the
/// alarm command/reply payload cases) and the bulk write/read command
/// family extension (`WriteBulk` / `Write2Bulk` / `WriteSecuredBulk` /
/// `WriteSecured2Bulk` / `ReadBulk` plus their `BulkWriteReply` and
/// `BulkReadReply` payloads) shipped under version 3 — both were strictly
/// additive contract changes, so neither required a further bump. A
/// future breaking contract change should bump this constant and update
/// this test in lock-step.
/// constant at 3. All three of the following extensions shipped under
/// version 3 as strictly additive contract changes that did not require a
/// further bump: (1) the alarm proto extension (<c>AcknowledgeAlarm</c> /
/// <c>QueryActiveAlarms</c> RPCs, the <c>OnAlarmTransitionEvent</c> body,
/// and the alarm command/reply payload cases); (2) the bulk write/read
/// command family (<c>WriteBulk</c> / <c>Write2Bulk</c> /
/// <c>WriteSecuredBulk</c> / <c>WriteSecured2Bulk</c> / <c>ReadBulk</c>
/// plus their <c>BulkWriteReply</c> and <c>BulkReadReply</c> payloads);
/// (3) the sparse-array write ergonomics extension (<c>MxSparseArray</c> /
/// <c>MxSparseElement</c> messages plus the <c>sparse_array_value = 19</c>
/// arm on the <c>MxValue</c> oneof). A future breaking contract change
/// should bump this constant and update this test in lock-step.
/// </summary>
[Fact]
public void GatewayProtocolVersion_IsVersionThree()
@@ -1588,4 +1588,87 @@ public sealed class ProtobufContractRoundTripTests
Assert.Equal(150UL, parsed.ReplayGap.RequestedAfterSequence);
Assert.Equal(200UL, parsed.ReplayGap.OldestAvailableSequence);
}
/// <summary>
/// Pins the wire field number for <c>MxValue.sparse_array_value</c> (19)
/// via the generated constant, pins the <see cref="MxSparseArray"/> and
/// <see cref="MxSparseElement"/> field numbers by name + number against the
/// descriptor, and round-trips an <see cref="MxValue"/> carrying a
/// <see cref="MxSparseArray"/> with at least one <see cref="MxSparseElement"/>
/// so a future renumber or type-narrowing is caught at the contract level.
/// Also verifies that an all-defaults <see cref="MxSparseArray"/> (no elements)
/// is not a proto-level error. See Contracts-023.
/// </summary>
[Fact]
public void MxValue_RoundTripsSparseArrayValueAndPinsFieldNumbers()
{
// Pin MxValue.sparse_array_value wire field number == 19.
Assert.Equal(19, MxValue.SparseArrayValueFieldNumber);
// Pin MxSparseArray field numbers by name + number.
var sparseArrayFields = MxSparseArray.Descriptor.Fields;
Assert.Equal(1, sparseArrayFields[MxSparseArray.ElementDataTypeFieldNumber].FieldNumber);
Assert.Equal("element_data_type", sparseArrayFields[MxSparseArray.ElementDataTypeFieldNumber].Name);
Assert.Equal(2, sparseArrayFields[MxSparseArray.TotalLengthFieldNumber].FieldNumber);
Assert.Equal("total_length", sparseArrayFields[MxSparseArray.TotalLengthFieldNumber].Name);
Assert.Equal(3, sparseArrayFields[MxSparseArray.ElementsFieldNumber].FieldNumber);
Assert.Equal("elements", sparseArrayFields[MxSparseArray.ElementsFieldNumber].Name);
// Pin MxSparseElement field numbers by name + number.
var sparseElementFields = MxSparseElement.Descriptor.Fields;
Assert.Equal(1, sparseElementFields[MxSparseElement.IndexFieldNumber].FieldNumber);
Assert.Equal("index", sparseElementFields[MxSparseElement.IndexFieldNumber].Name);
Assert.Equal(2, sparseElementFields[MxSparseElement.ValueFieldNumber].FieldNumber);
Assert.Equal("value", sparseElementFields[MxSparseElement.ValueFieldNumber].Name);
// Round-trip an MxValue with a populated MxSparseArray (one scalar element).
var original = new MxValue
{
DataType = MxDataType.Float,
SparseArrayValue = new MxSparseArray
{
ElementDataType = MxDataType.Float,
TotalLength = 4,
Elements =
{
new MxSparseElement
{
Index = 2,
Value = new MxValue
{
DataType = MxDataType.Float,
FloatValue = 3.14f,
VariantType = "VT_R4",
},
},
},
},
};
var parsed = MxValue.Parser.ParseFrom(original.ToByteArray());
Assert.Equal(original, parsed);
Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, parsed.KindCase);
Assert.NotNull(parsed.SparseArrayValue);
Assert.Equal(MxDataType.Float, parsed.SparseArrayValue.ElementDataType);
Assert.Equal(4u, parsed.SparseArrayValue.TotalLength);
var element = Assert.Single(parsed.SparseArrayValue.Elements);
Assert.Equal(2u, element.Index);
Assert.Equal(3.14f, element.Value.FloatValue);
// An all-defaults MxSparseArray (no elements) is not a proto-level error.
var empty = new MxValue
{
DataType = MxDataType.Float,
SparseArrayValue = new MxSparseArray
{
ElementDataType = MxDataType.Float,
TotalLength = 10,
},
};
var parsedEmpty = MxValue.Parser.ParseFrom(empty.ToByteArray());
Assert.Equal(empty, parsedEmpty);
Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, parsedEmpty.KindCase);
Assert.Empty(parsedEmpty.SparseArrayValue.Elements);
}
}
@@ -247,6 +247,440 @@ public sealed class GatewayArrayWriteWiringTests
Assert.Equal(new[] { 0, 7, 0, 0 }, forwarded.ArrayValue.Int32Values.Values);
}
/// <summary>
/// A bare array address added via <c>AddItemBulk</c> is normalized to its writable array form
/// on the wire (so the worker registers a write-capable handle), while a scalar address in the
/// same batch is forwarded unchanged. Tracking the worker's echoed reply lands the normalized
/// address in the <see cref="SessionItemRegistration"/>.
/// </summary>
[Fact]
public async Task AddItemBulk_BareArrayAddress_NormalizedOnWireAndInRegistration()
{
CapturingWorkerClient worker = new();
GatewaySession session = CreateReadySession(worker);
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.AddItemBulk,
AddItemBulk = new AddItemBulkCommand
{
ServerHandle = 1,
TagAddresses = { "Obj.Arr", "Obj.Scalar" },
},
},
};
await session.InvokeAsync(command, CancellationToken.None);
// The array address gains the writable "[]" suffix; the scalar passes through unchanged.
Assert.NotNull(worker.LastCommand);
Assert.Equal(
new[] { "Obj.Arr[]", "Obj.Scalar" },
worker.LastCommand!.Command.AddItemBulk.TagAddresses);
// The real worker echoes back the (suffixed) address it bound; tracking the reply must land the
// normalized address in the registration so a later write resolves the write-capable handle.
MxCommand trackingCopy = new()
{
Kind = MxCommandKind.AddItemBulk,
AddItemBulk = new AddItemBulkCommand
{
ServerHandle = 1,
TagAddresses = { "Obj.Arr", "Obj.Scalar" },
},
};
MxCommandReply reply = new()
{
Kind = MxCommandKind.AddItemBulk,
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
AddItemBulk = new BulkSubscribeReply
{
Results =
{
new SubscribeResult
{
ServerHandle = 1,
ItemHandle = 50,
TagAddress = "Obj.Arr[]",
WasSuccessful = true,
},
new SubscribeResult
{
ServerHandle = 1,
ItemHandle = 51,
TagAddress = "Obj.Scalar",
WasSuccessful = true,
},
},
},
};
session.TrackCommandReply(trackingCopy, reply);
Assert.True(session.TryGetItemRegistration(1, 50, out SessionItemRegistration arrayRegistration));
Assert.Equal("Obj.Arr[]", arrayRegistration.TagAddress);
Assert.True(session.TryGetItemRegistration(1, 51, out SessionItemRegistration scalarRegistration));
Assert.Equal("Obj.Scalar", scalarRegistration.TagAddress);
}
/// <summary>
/// A sparse-array <see cref="WriteSecuredCommand"/> value is expanded to a full,
/// default-filled <see cref="MxArray"/> before reaching the worker; the secured variant's
/// <c>case</c> arm in <c>NormalizeOutboundCommand</c> is wired to the expander.
/// </summary>
[Fact]
public async Task WriteSecured_SparseArrayValue_ExpandedBeforeReachingWorker()
{
CapturingWorkerClient worker = new();
GatewaySession session = CreateReadySession(worker);
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.WriteSecured,
WriteSecured = new WriteSecuredCommand
{
ServerHandle = 1,
ItemHandle = 42,
Value = new MxValue
{
SparseArrayValue = new MxSparseArray
{
ElementDataType = MxDataType.Integer,
TotalLength = 4,
Elements =
{
new MxSparseElement
{
Index = 2,
Value = new MxValue { Int32Value = 9 },
},
},
},
},
},
},
};
await session.InvokeAsync(command, CancellationToken.None);
MxValue forwarded = worker.LastCommand!.Command.WriteSecured.Value;
Assert.Equal(MxValue.KindOneofCase.ArrayValue, forwarded.KindCase);
Assert.Equal(new[] { 0, 0, 9, 0 }, forwarded.ArrayValue.Int32Values.Values);
}
/// <summary>
/// A sparse-array <see cref="Write2Command"/> (timestamped) value is expanded to a full,
/// default-filled <see cref="MxArray"/> before reaching the worker; the Write2 variant's
/// <c>case</c> arm in <c>NormalizeOutboundCommand</c> is wired to the expander.
/// </summary>
[Fact]
public async Task Write2_SparseArrayValue_ExpandedBeforeReachingWorker()
{
CapturingWorkerClient worker = new();
GatewaySession session = CreateReadySession(worker);
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.Write2,
Write2 = new Write2Command
{
ServerHandle = 1,
ItemHandle = 42,
Value = new MxValue
{
SparseArrayValue = new MxSparseArray
{
ElementDataType = MxDataType.Integer,
TotalLength = 4,
Elements =
{
new MxSparseElement
{
Index = 3,
Value = new MxValue { Int32Value = 5 },
},
},
},
},
},
},
};
await session.InvokeAsync(command, CancellationToken.None);
MxValue forwarded = worker.LastCommand!.Command.Write2.Value;
Assert.Equal(MxValue.KindOneofCase.ArrayValue, forwarded.KindCase);
Assert.Equal(new[] { 0, 0, 0, 5 }, forwarded.ArrayValue.Int32Values.Values);
}
/// <summary>
/// A sparse-array <see cref="WriteSecured2Command"/> (timestamped secured) value is expanded
/// to a full, default-filled <see cref="MxArray"/> before reaching the worker; the
/// WriteSecured2 variant's <c>case</c> arm in <c>NormalizeOutboundCommand</c> is wired to
/// the expander.
/// </summary>
[Fact]
public async Task WriteSecured2_SparseArrayValue_ExpandedBeforeReachingWorker()
{
CapturingWorkerClient worker = new();
GatewaySession session = CreateReadySession(worker);
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.WriteSecured2,
WriteSecured2 = new WriteSecured2Command
{
ServerHandle = 1,
ItemHandle = 42,
Value = new MxValue
{
SparseArrayValue = new MxSparseArray
{
ElementDataType = MxDataType.Integer,
TotalLength = 4,
Elements =
{
new MxSparseElement
{
Index = 0,
Value = new MxValue { Int32Value = 3 },
},
},
},
},
},
},
};
await session.InvokeAsync(command, CancellationToken.None);
MxValue forwarded = worker.LastCommand!.Command.WriteSecured2.Value;
Assert.Equal(MxValue.KindOneofCase.ArrayValue, forwarded.KindCase);
Assert.Equal(new[] { 3, 0, 0, 0 }, forwarded.ArrayValue.Int32Values.Values);
}
/// <summary>
/// A sparse-array entry in a <see cref="Write2BulkCommand"/> (timestamped) is expanded to a
/// full, default-filled <see cref="MxArray"/> before reaching the worker; the Write2Bulk
/// variant's <c>case</c> arm in <c>NormalizeOutboundCommand</c> is wired to the expander.
/// </summary>
[Fact]
public async Task Write2Bulk_SparseArrayEntryValue_ExpandedBeforeReachingWorker()
{
CapturingWorkerClient worker = new();
GatewaySession session = CreateReadySession(worker);
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.Write2Bulk,
Write2Bulk = new Write2BulkCommand
{
ServerHandle = 1,
Entries =
{
new Write2BulkEntry
{
ItemHandle = 42,
Value = new MxValue
{
SparseArrayValue = new MxSparseArray
{
ElementDataType = MxDataType.Integer,
TotalLength = 4,
Elements =
{
new MxSparseElement
{
Index = 1,
Value = new MxValue { Int32Value = 11 },
},
},
},
},
},
},
},
},
};
await session.InvokeAsync(command, CancellationToken.None);
MxValue forwarded = worker.LastCommand!.Command.Write2Bulk.Entries[0].Value;
Assert.Equal(MxValue.KindOneofCase.ArrayValue, forwarded.KindCase);
Assert.Equal(new[] { 0, 11, 0, 0 }, forwarded.ArrayValue.Int32Values.Values);
}
/// <summary>
/// A sparse-array entry in a <see cref="WriteSecuredBulkCommand"/> is expanded to a full,
/// default-filled <see cref="MxArray"/> before reaching the worker; the WriteSecuredBulk
/// variant's <c>case</c> arm in <c>NormalizeOutboundCommand</c> is wired to the expander.
/// </summary>
[Fact]
public async Task WriteSecuredBulk_SparseArrayEntryValue_ExpandedBeforeReachingWorker()
{
CapturingWorkerClient worker = new();
GatewaySession session = CreateReadySession(worker);
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.WriteSecuredBulk,
WriteSecuredBulk = new WriteSecuredBulkCommand
{
ServerHandle = 1,
Entries =
{
new WriteSecuredBulkEntry
{
ItemHandle = 42,
Value = new MxValue
{
SparseArrayValue = new MxSparseArray
{
ElementDataType = MxDataType.Integer,
TotalLength = 4,
Elements =
{
new MxSparseElement
{
Index = 2,
Value = new MxValue { Int32Value = 13 },
},
},
},
},
},
},
},
},
};
await session.InvokeAsync(command, CancellationToken.None);
MxValue forwarded = worker.LastCommand!.Command.WriteSecuredBulk.Entries[0].Value;
Assert.Equal(MxValue.KindOneofCase.ArrayValue, forwarded.KindCase);
Assert.Equal(new[] { 0, 0, 13, 0 }, forwarded.ArrayValue.Int32Values.Values);
}
/// <summary>
/// A sparse-array entry in a <see cref="WriteSecured2BulkCommand"/> (timestamped secured) is
/// expanded to a full, default-filled <see cref="MxArray"/> before reaching the worker; the
/// WriteSecured2Bulk variant's <c>case</c> arm in <c>NormalizeOutboundCommand</c> is wired to
/// the expander.
/// </summary>
[Fact]
public async Task WriteSecured2Bulk_SparseArrayEntryValue_ExpandedBeforeReachingWorker()
{
CapturingWorkerClient worker = new();
GatewaySession session = CreateReadySession(worker);
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.WriteSecured2Bulk,
WriteSecured2Bulk = new WriteSecured2BulkCommand
{
ServerHandle = 1,
Entries =
{
new WriteSecured2BulkEntry
{
ItemHandle = 42,
Value = new MxValue
{
SparseArrayValue = new MxSparseArray
{
ElementDataType = MxDataType.Integer,
TotalLength = 4,
Elements =
{
new MxSparseElement
{
Index = 3,
Value = new MxValue { Int32Value = 17 },
},
},
},
},
},
},
},
},
};
await session.InvokeAsync(command, CancellationToken.None);
MxValue forwarded = worker.LastCommand!.Command.WriteSecured2Bulk.Entries[0].Value;
Assert.Equal(MxValue.KindOneofCase.ArrayValue, forwarded.KindCase);
Assert.Equal(new[] { 0, 0, 0, 17 }, forwarded.ArrayValue.Int32Values.Values);
}
/// <summary>
/// A bare array address added via <c>AddBufferedItem</c> is normalized to its writable array
/// form on the wire and in the tracked <see cref="SessionItemRegistration"/>.
/// </summary>
[Fact]
public async Task AddBufferedItem_BareArrayAddress_NormalizedOnWireAndInRegistration()
{
CapturingWorkerClient worker = new();
GatewaySession session = CreateReadySession(worker);
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.AddBufferedItem,
AddBufferedItem = new AddBufferedItemCommand
{
ServerHandle = 1,
ItemDefinition = "Obj.Arr",
},
},
};
worker.NextReply = new WorkerCommandReply
{
Reply = new MxCommandReply
{
Kind = MxCommandKind.AddBufferedItem,
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
AddBufferedItem = new AddBufferedItemReply { ItemHandle = 60 },
},
};
await session.InvokeAsync(command, CancellationToken.None);
Assert.NotNull(worker.LastCommand);
Assert.Equal("Obj.Arr[]", worker.LastCommand!.Command.AddBufferedItem.ItemDefinition);
// AddBufferedItem tracking keys off the command's ItemDefinition (the reply carries no address),
// so the tracking-path normalization must run for the registration to match the bound handle.
MxCommand trackingCopy = new()
{
Kind = MxCommandKind.AddBufferedItem,
AddBufferedItem = new AddBufferedItemCommand
{
ServerHandle = 1,
ItemDefinition = "Obj.Arr",
},
};
session.TrackCommandReply(trackingCopy, worker.NextReply.Reply);
Assert.True(session.TryGetItemRegistration(1, 60, out SessionItemRegistration registration));
Assert.Equal("Obj.Arr[]", registration.TagAddress);
}
private static GatewaySession CreateReadySession(IWorkerClient workerClient)
{
GatewaySession session = new(
@@ -263,6 +263,116 @@ public sealed class ConstraintEnforcerTests
Assert.Equal("tag_metadata", unknown.ConstraintName);
}
/// <summary>
/// The <c>[]</c>-suffix fallback widened *resolution* of a bare array name, not *authorization*:
/// a bare array attribute that resolves through the fallback but is outside the key's read scope
/// must still be denied with a <c>read_scope</c> failure (Server-058).
/// </summary>
[Fact]
public async Task CheckReadTagAsync_WithBareArrayName_OutOfScope_StillDeniedReadScope()
{
ConstraintEnforcer enforcer = CreateEnforcer(out _);
ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
{
// Scope covers a different object, so the resolved array attribute is out of scope.
ReadTagGlobs = ["Other_001.*"],
});
ConstraintFailure? failure = await enforcer.CheckReadTagAsync(
identity,
"Pump_001.Levels",
CancellationToken.None);
Assert.NotNull(failure);
Assert.Equal("read_scope", failure.ConstraintName);
}
/// <summary>
/// A write against an array handle whose registration carries the suffixed form ("Pump_001.Levels[]")
/// resolves through <c>ResolveTarget</c> and is denied with a <c>write_scope</c> failure when the
/// array attribute is outside the key's write scope (Server-058).
/// </summary>
[Fact]
public async Task CheckWriteHandleAsync_WithSuffixedArrayRegistration_OutOfScope_StillDeniedWriteScope()
{
ConstraintEnforcer enforcer = CreateEnforcer(out _);
ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
{
WriteSubtrees = ["Other/*"],
});
GatewaySession session = CreateSession();
session.TrackCommandReply(
new MxCommand
{
Kind = MxCommandKind.AddItem,
AddItem = new AddItemCommand
{
ServerHandle = 12,
// The worker-bound, suffixed array address is what lands in the registration.
ItemDefinition = "Pump_001.Levels[]",
},
},
new MxCommandReply
{
ProtocolStatus = ZB.MOM.WW.MxGateway.Server.Grpc.MxAccessGrpcMapper.Ok(),
AddItem = new AddItemReply { ItemHandle = 70 },
});
ConstraintFailure? failure = await enforcer.CheckWriteHandleAsync(
identity,
session,
serverHandle: 12,
itemHandle: 70,
CancellationToken.None);
Assert.NotNull(failure);
Assert.Equal("write_scope", failure.ConstraintName);
}
/// <summary>
/// A write against an in-scope array handle whose registration carries the suffixed form is still
/// denied when the array attribute's <c>SecurityClassification</c> exceeds the key's
/// <c>MaxWriteClassification</c>, resolved through <c>ResolveTarget</c> via the suffixed address
/// (Server-058).
/// </summary>
[Fact]
public async Task CheckWriteHandleAsync_WithSuffixedArrayRegistration_ClassificationTooHigh_StillDenied()
{
ConstraintEnforcer enforcer = CreateEnforcer(out _);
ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
{
// In scope for the array attribute, but the array's classification (2) exceeds the cap (1).
WriteTagGlobs = ["Pump_001.*"],
MaxWriteClassification = 1,
});
GatewaySession session = CreateSession();
session.TrackCommandReply(
new MxCommand
{
Kind = MxCommandKind.AddItem,
AddItem = new AddItemCommand
{
ServerHandle = 12,
ItemDefinition = "Pump_001.Setpoints[]",
},
},
new MxCommandReply
{
ProtocolStatus = ZB.MOM.WW.MxGateway.Server.Grpc.MxAccessGrpcMapper.Ok(),
AddItem = new AddItemReply { ItemHandle = 71 },
});
ConstraintFailure? failure = await enforcer.CheckWriteHandleAsync(
identity,
session,
serverHandle: 12,
itemHandle: 71,
CancellationToken.None);
Assert.NotNull(failure);
Assert.Equal("max_write_classification", failure.ConstraintName);
}
private static ConstraintEnforcer CreateEnforcer(out FakeAuditWriter auditWriter)
{
auditWriter = new FakeAuditWriter();
@@ -340,6 +450,16 @@ public sealed class ConstraintEnforcerTests
FullTagReference = "Pump_001.Levels[]",
IsArray = true,
},
new GalaxyAttribute
{
// A second array attribute carrying a non-zero security classification so
// the MaxWriteClassification check can be exercised via a suffixed
// registration address resolving through ResolveTarget.
AttributeName = "Setpoints",
FullTagReference = "Pump_001.Setpoints[]",
IsArray = true,
SecurityClassification = 2,
},
},
},
new GalaxyObject