diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/LiveGatewayWrite2Tests.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/LiveGatewayWrite2Tests.cs
new file mode 100644
index 00000000..cce6fb07
--- /dev/null
+++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/LiveGatewayWrite2Tests.cs
@@ -0,0 +1,203 @@
+using System.Threading.Channels;
+using Google.Protobuf.WellKnownTypes;
+using Xunit.Abstractions;
+using ZB.MOM.WW.MxGateway.Contracts.Proto;
+
+namespace ZB.MOM.WW.MxGateway.Client.Tests;
+
+///
+/// Live proof that Write2 applies a value and timestamp through a real gateway (#212).
+/// The item is advised supervisory first: MXAccess only accepts a user-id-0 write on a
+/// supervisory-advised item, and a plain advise gets the write refused (or never completed).
+/// The original value is restored with a plain Write before the test returns.
+///
+public sealed class LiveGatewayWrite2Tests(ITestOutputHelper output)
+{
+ private static readonly TimeSpan EventTimeout = TimeSpan.FromSeconds(20);
+
+ /// Write2 on a supervisory-advised item applies the value; the original is restored.
+ /// A task that represents the asynchronous operation.
+ [LiveGatewayWriteFact]
+ public async Task Write2_SupervisoryAdvise_AppliesValue()
+ {
+ Write2Outcome outcome = await RunWrite2RoundTripAsync();
+
+ Assert.Equal(outcome.WrittenValue, outcome.ObservedValue);
+ Assert.Equal(outcome.OriginalValue, outcome.RestoredValue);
+ }
+
+ ///
+ /// The source timestamp after Write2 equals the timestamp sent. On a host whose clock is not
+ /// UTC this fails until mxaccessgw#228 is fixed (MXAccess reads the VT_DATE as local time).
+ ///
+ /// A task that represents the asynchronous operation.
+ [LiveGatewayWriteFact(requireTimestampOptIn: true)]
+ public async Task Write2_SupervisoryAdvise_KeepsSentTimestamp()
+ {
+ Write2Outcome outcome = await RunWrite2RoundTripAsync();
+
+ Assert.Equal(outcome.WrittenValue, outcome.ObservedValue);
+ Assert.Equal(outcome.SentTimestampUtc, outcome.ObservedTimestampUtc);
+ }
+
+ private async Task RunWrite2RoundTripAsync()
+ {
+ string item = LiveGatewayWriteFactAttribute.WriteItem;
+ await using MxGatewayClient client = MxGatewayClient.Create(new MxGatewayClientOptions
+ {
+ Endpoint = new Uri(LiveGatewayWriteFactAttribute.Endpoint),
+ ApiKey = LiveGatewayWriteFactAttribute.ApiKey,
+ });
+
+ MxGatewaySession session = await client.OpenSessionAsync(new OpenSessionRequest
+ {
+ ClientSessionName = "live-gateway-write2",
+ CommandTimeout = Duration.FromTimeSpan(TimeSpan.FromSeconds(30)),
+ });
+ output.WriteLine($"session {session.SessionId}, item {item}");
+
+ Channel events = Channel.CreateUnbounded();
+ using CancellationTokenSource streamCancellation = new();
+ Task streamTask = Task.Run(async () =>
+ {
+ try
+ {
+ await foreach (MxEvent mxEvent in session.StreamEventsAsync(0, streamCancellation.Token))
+ {
+ events.Writer.TryWrite(mxEvent);
+ }
+ }
+ catch (Exception) when (streamCancellation.IsCancellationRequested)
+ {
+ // Expected at teardown.
+ }
+ });
+
+ int serverHandle = 0;
+ int itemHandle = 0;
+ int? originalValue = null;
+ bool restored = false;
+ try
+ {
+ serverHandle = await session.RegisterAsync("live-gateway-write2");
+ itemHandle = await session.AddItemAsync(serverHandle, item);
+ await session.AdviseSupervisoryAsync(serverHandle, itemHandle);
+
+ MxEvent initial = await WaitForAsync(events, MxEventFamily.OnDataChange, itemHandle);
+ Assert.Equal(MxValue.KindOneofCase.Int32Value, initial.Value.KindCase);
+ originalValue = initial.Value.Int32Value;
+ int writtenValue = originalValue == 212212 ? 212213 : 212212;
+
+ DateTime sent = DateTime.UtcNow.AddSeconds(-30);
+ sent = new DateTime(sent.Ticks - (sent.Ticks % TimeSpan.TicksPerSecond), DateTimeKind.Utc);
+ output.WriteLine($"before: {originalValue} @ {Format(initial.SourceTimestamp)}; Write2 {writtenValue} @ {sent:O}");
+
+ MxCommandReply write2Reply = await session.Write2RawAsync(
+ serverHandle,
+ itemHandle,
+ new MxValue { DataType = MxDataType.Integer, Int32Value = writtenValue },
+ new MxValue { DataType = MxDataType.Time, VariantType = "VT_DATE", TimestampValue = Timestamp.FromDateTime(sent) },
+ userId: 0);
+ Assert.Equal(ProtocolStatusCode.Ok, write2Reply.ProtocolStatus.Code);
+ Assert.Equal(MxCommandKind.Write2, write2Reply.Kind);
+
+ (MxEvent written, MxEvent completion) = await WaitForWriteAsync(events, itemHandle);
+ Assert.All(completion.Statuses, status => Assert.Equal(MxStatusCategory.Ok, status.Category));
+ output.WriteLine($"after Write2: {written.Value.Int32Value} @ {Format(written.SourceTimestamp)}");
+
+ MxCommandReply restoreReply = await session.WriteRawAsync(
+ serverHandle,
+ itemHandle,
+ new MxValue { DataType = MxDataType.Integer, Int32Value = originalValue.Value },
+ userId: 0);
+ Assert.Equal(ProtocolStatusCode.Ok, restoreReply.ProtocolStatus.Code);
+ (MxEvent restoredEvent, _) = await WaitForWriteAsync(events, itemHandle);
+ restored = true;
+ output.WriteLine($"restored: {restoredEvent.Value.Int32Value} @ {Format(restoredEvent.SourceTimestamp)}");
+
+ return new Write2Outcome(
+ originalValue.Value,
+ writtenValue,
+ written.Value.Int32Value,
+ sent,
+ written.SourceTimestamp?.ToDateTime(),
+ restoredEvent.Value.Int32Value);
+ }
+ finally
+ {
+ if (!restored && originalValue is not null && itemHandle != 0)
+ {
+ // Best effort: never leave the test value behind when an assertion failed
+ // mid-way. Logged, not thrown, so the original failure is not masked.
+ try
+ {
+ MxCommandReply reply = await session.WriteRawAsync(
+ serverHandle,
+ itemHandle,
+ new MxValue { DataType = MxDataType.Integer, Int32Value = originalValue.Value },
+ userId: 0);
+ output.WriteLine($"restore after failure: {originalValue} -> {reply.ProtocolStatus.Code}");
+ }
+ catch (Exception ex)
+ {
+ output.WriteLine($"restore after failure threw {ex.GetType().Name}: {ex.Message}");
+ }
+ }
+
+ await session.CloseAsync();
+ streamCancellation.Cancel();
+ await streamTask;
+ }
+ }
+
+ private static async Task WaitForAsync(Channel events, MxEventFamily family, int itemHandle)
+ {
+ using CancellationTokenSource timeout = new(EventTimeout);
+ while (true)
+ {
+ MxEvent mxEvent = await events.Reader.ReadAsync(timeout.Token);
+ if (mxEvent.Family == family && mxEvent.ItemHandle == itemHandle)
+ {
+ return mxEvent;
+ }
+ }
+ }
+
+ /// Waits for the OnDataChange and OnWriteComplete a write raises, in either order.
+ private static async Task<(MxEvent DataChange, MxEvent Completion)> WaitForWriteAsync(Channel events, int itemHandle)
+ {
+ using CancellationTokenSource timeout = new(EventTimeout);
+ MxEvent? dataChange = null;
+ MxEvent? completion = null;
+ while (dataChange is null || completion is null)
+ {
+ MxEvent mxEvent = await events.Reader.ReadAsync(timeout.Token);
+ if (mxEvent.ItemHandle != itemHandle)
+ {
+ continue;
+ }
+
+ if (mxEvent.Family == MxEventFamily.OnDataChange)
+ {
+ dataChange = mxEvent;
+ }
+ else if (mxEvent.Family == MxEventFamily.OnWriteComplete)
+ {
+ completion = mxEvent;
+ }
+ }
+
+ return (dataChange, completion);
+ }
+
+ private static string Format(Timestamp? timestamp) =>
+ timestamp is null ? "-" : timestamp.ToDateTime().ToString("O");
+
+ private sealed record Write2Outcome(
+ int OriginalValue,
+ int WrittenValue,
+ int ObservedValue,
+ DateTime SentTimestampUtc,
+ DateTime? ObservedTimestampUtc,
+ int RestoredValue);
+}
diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/LiveGatewayWriteFactAttribute.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/LiveGatewayWriteFactAttribute.cs
new file mode 100644
index 00000000..424f0c41
--- /dev/null
+++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/LiveGatewayWriteFactAttribute.cs
@@ -0,0 +1,57 @@
+namespace ZB.MOM.WW.MxGateway.Client.Tests;
+
+///
+/// Marks a test that writes to a real Galaxy attribute through a running gateway.
+/// The test is skipped unless an endpoint, an API key and a write item are all set,
+/// so it never runs (or writes) by accident. See docs/GatewayTesting.md, "Live gateway write".
+///
+public sealed class LiveGatewayWriteFactAttribute : FactAttribute
+{
+ /// Gateway gRPC endpoint, e.g. http://host:5120.
+ public const string EndpointVariableName = "MXGATEWAY_LIVE_GATEWAY_ENDPOINT";
+
+ /// API key (mxgw_<id>_<secret>). Prefer the file variant so the key stays out of the environment.
+ public const string ApiKeyVariableName = "MXGATEWAY_LIVE_GATEWAY_API_KEY";
+
+ /// Path to a file holding the API key. Takes precedence over .
+ public const string ApiKeyFileVariableName = "MXGATEWAY_LIVE_GATEWAY_API_KEY_FILE";
+
+ /// A writable, test-only Int32 attribute. It is written and then restored. No default on purpose.
+ public const string WriteItemVariableName = "MXGATEWAY_LIVE_GATEWAY_WRITE_ITEM";
+
+ /// Set to 1 to also run the Write2 timestamp-parity test (fails on a non-UTC host until #228 is fixed).
+ public const string AssertWrite2TimestampVariableName = "MXGATEWAY_LIVE_GATEWAY_ASSERT_WRITE2_TIMESTAMP";
+
+ /// Initializes the attribute, skipping unless the live gateway write variables are set.
+ /// When true, also require =1.
+ public LiveGatewayWriteFactAttribute(bool requireTimestampOptIn = false)
+ {
+ if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(EndpointVariableName))
+ || string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(WriteItemVariableName))
+ || (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ApiKeyVariableName))
+ && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ApiKeyFileVariableName))))
+ {
+ Skip = $"Set {EndpointVariableName}, {WriteItemVariableName} and {ApiKeyFileVariableName} (or {ApiKeyVariableName}) to run live gateway write tests.";
+ }
+ else if (requireTimestampOptIn
+ && Environment.GetEnvironmentVariable(AssertWrite2TimestampVariableName) != "1")
+ {
+ Skip = $"Set {AssertWrite2TimestampVariableName}=1 to assert Write2 timestamp parity (mxaccessgw#228).";
+ }
+ }
+
+ internal static string Endpoint => Environment.GetEnvironmentVariable(EndpointVariableName)!;
+
+ internal static string WriteItem => Environment.GetEnvironmentVariable(WriteItemVariableName)!;
+
+ internal static string ApiKey
+ {
+ get
+ {
+ string? path = Environment.GetEnvironmentVariable(ApiKeyFileVariableName);
+ return !string.IsNullOrWhiteSpace(path)
+ ? File.ReadAllText(path).Trim()
+ : Environment.GetEnvironmentVariable(ApiKeyVariableName)!.Trim();
+ }
+ }
+}
diff --git a/code-reviews/IntegrationTests/findings.md b/code-reviews/IntegrationTests/findings.md
index 7d596e54..2a0a5de2 100644
--- a/code-reviews/IntegrationTests/findings.md
+++ b/code-reviews/IntegrationTests/findings.md
@@ -716,3 +716,5 @@ The prior `DashboardAuthenticator` ctor took `IOptions`, so the
**Resolution:** 2026-06-16: requires a live MXAccess rig + provider state not available on this dev box; add the AddItem2/Write2 parity assertions when running on the MXAccess host. → #212
2026-11-12: Resolved. `AddItem2` has worker-level live coverage (`Worker.Tests/MxAccess/MxAccessLiveComCreationTests.cs`); `Write2` is covered by `WorkerLiveMxAccessSmokeTests.GatewaySession_WithLiveWorker_Write2ValueWithTimestampToAdvisedItem` (`9c6ac0cd`), run live on windev at `04a40f2c` (x86 Release worker, item `TestChildObject.TestInt`) and PASSED, alone and with the rest of the class (10/10, `WriteSecured` excluded). `Write2` replied `ProtocolStatusCode.Ok`, hresult `0`, kind `Write2`, and MXAccess raised a matching `OnWriteComplete`. The MXAccess status on that completion was `success=0 category=SecurityError detail=1008`: the item's Galaxy security refuses an unauthenticated write, and `Write2` carries no user id. Plain `Write` got the identical refusal in the same run, and the value stayed at 7004 with an unchanged source timestamp. So the live run proves `Write2` reaches the COM call and comes back with a real provider status, not an `InvalidRequest` short-circuit. It does not prove that a value plus timestamp is *applied*, because the rig has no free-access integer test attribute. → #212 (closed)
+
+2026-11-12 (later), correction: the "no free-access attribute on the rig" limit was wrong, or at least unproven. The windev test used a **plain** `Advise`, and MXAccess refuses a user-id-0 write on a plainly advised item with exactly that `SecurityError/1008`. On the DEV gateway (wonder-app-vd03, `2b13564e`), `MESReceiver_025.MoveInBatchID` (Int32, Z28062) behaved the same way: after `AdviseSupervisory`, `Write2` **applied** the value (`0` → `212212`, OnWriteComplete `Ok`/`RespondingAutomationObject`, then restored to `0`), and after a plain `Advise` the same `Write2` got `SecurityError/1008` and nothing changed. The value-applied proof is now the opt-in `clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/LiveGatewayWrite2Tests.cs` (env vars in `docs/GatewayTesting.md`, "Live gateway write"). The windev test now uses `AdviseSupervisory` and restores the original value. It has **not** been re-run on windev since that change. The same run found that the timestamp is stored shifted by the host's UTC offset (sent `01:33:00Z`, stored `06:33:00Z` on the UTC-5 box) → #228.
diff --git a/docs/GatewayTesting.md b/docs/GatewayTesting.md
index 9e12d9a2..d5e055d6 100644
--- a/docs/GatewayTesting.md
+++ b/docs/GatewayTesting.md
@@ -51,7 +51,7 @@ shutdown request even when a command or event assertion fails. Cleanup failures
in that `finally` block are logged rather than thrown, so a real assertion
failure is never masked by a shutdown timeout.
-`WorkerLiveMxAccessSmokeTests` additionally covers seven MXAccess parity paths the
+`WorkerLiveMxAccessSmokeTests` additionally covers eight MXAccess parity paths the
fake-worker tests cannot validate:
- a `Write` round-trip against an advised item, asserting both that the reply is
@@ -72,6 +72,13 @@ fake-worker tests cannot validate:
gateway must transition the session to `SessionState.Faulted` with a
non-empty fault description carrying a known worker-client classification
(pipe disconnected / worker faulted / end-of-stream / heartbeat expired),
+- a `Write2` (value + `VT_DATE` timestamp) round-trip after `AdviseSupervisory`,
+ asserting the reply is `Ok` / `MxCommandKind.Write2` and a matching
+ `OnWriteComplete` arrives, then restoring the original value with a plain
+ `Write`. It uses a supervisory advise because MXAccess refuses a user-id-0
+ write on a plainly advised item with `SecurityError`/`1008` (#212). The
+ completion status is logged, not asserted, because whether the windev item
+ accepts the write has not been checked since the switch,
- the B8 new COM commands — `AuthenticateUser`, `ArchestrAUserToId`, `Suspend`,
and `Activate` — each asserting a real MXAccess reply (not `InvalidRequest`)
is returned against an added-but-not-advised item, and
@@ -81,7 +88,7 @@ fake-worker tests cannot validate:
or dropping frames; live §3.2 multi-sample conversion is noted as a residual
when the rig does not drive sample-bearing buffered batches on demand.
-All eight tests are gated by the same `MXGATEWAY_RUN_LIVE_MXACCESS_TESTS=1`
+All nine tests are gated by the same `MXGATEWAY_RUN_LIVE_MXACCESS_TESTS=1`
opt-in variable. Opt-in does not mean unscheduled: the `nightly-windev` job runs
this suite on windev every night at 06:00 UTC and files a Gitea issue when it goes
red (see [Continuous Integration](#continuous-integration)), so the smoke no longer
@@ -122,6 +129,36 @@ The test output includes session id, worker process id, command status,
HRESULT/status diagnostics, event sequence and handles, close status, and worker
stdout/stderr lines emitted during the run.
+## Live gateway write (Client.Tests)
+
+`LiveGatewayWrite2Tests` in `clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/` drives a
+**running gateway** over gRPC with the .NET client (no worker launched by the test), so
+it can run from any OS against a deployed box. It writes to a real Galaxy attribute,
+so it is skipped unless all of these are set:
+
+| Variable | Meaning |
+|---|---|
+| `MXGATEWAY_LIVE_GATEWAY_ENDPOINT` | Gateway gRPC endpoint, e.g. `http://:5120`. |
+| `MXGATEWAY_LIVE_GATEWAY_API_KEY_FILE` | File (mode 0600) holding the `mxgw_...` key. `MXGATEWAY_LIVE_GATEWAY_API_KEY` works too, but the file keeps the key out of the environment. The key needs `session:open`, `session:close`, `invoke:read`, `invoke:write`, `events:read`; a `Write tag globs` constraint scoped to the test item is enough. |
+| `MXGATEWAY_LIVE_GATEWAY_WRITE_ITEM` | A test-only, writable **Int32** attribute. No default on purpose. On the DEV box use a Z28062 receiver attribute such as `MESReceiver_025.MoveInBatchID`, never anything on Z28061. |
+| `MXGATEWAY_LIVE_GATEWAY_ASSERT_WRITE2_TIMESTAMP` | `1` also runs `Write2_SupervisoryAdvise_KeepsSentTimestamp`. On a host whose clock is not UTC it fails until #228 is fixed. |
+
+Each test does Register, AddItem, **AdviseSupervisory**, reads the original value from the first
+`OnDataChange`, `Write2`s a different value with a timestamp 30 s in the past, waits for the
+`OnDataChange` and `OnWriteComplete` (asserting an `Ok` completion), then restores the original
+value with a plain `Write` (also on any failure after the original was read).
+`Write2_SupervisoryAdvise_AppliesValue` asserts the value was applied and restored.
+
+```bash
+MXGATEWAY_LIVE_GATEWAY_ENDPOINT=http://wonder-app-vd03.zmr.zimmer.com:5120 \
+MXGATEWAY_LIVE_GATEWAY_API_KEY_FILE=/path/to/key.txt \
+MXGATEWAY_LIVE_GATEWAY_WRITE_ITEM=MESReceiver_025.MoveInBatchID \
+dotnet test clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests --filter FullyQualifiedName~LiveGatewayWrite2Tests
+```
+
+Run on the DEV box (vd03, gateway `2b13564e`) on 2026-11-12: the value test passed, and the
+timestamp test failed with exactly the #228 shift (sent `01:36:51Z`, stored `06:36:51Z`; vd03 is UTC-5).
+
## Dev-rig Probes
`src/ZB.MOM.WW.MxGateway.Worker.Tests/Probes/` partitions runtime probes from the regular
diff --git a/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs b/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs
index cb8269f9..d5f3f588 100644
--- a/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs
@@ -256,6 +256,10 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
string? sessionId = null;
Task? streamTask = null;
using CancellationTokenSource streamCancellation = new();
+ MxValue? originalValue = null;
+ bool restored = false;
+ int serverHandle = 0;
+ int itemHandle = 0;
try
{
@@ -288,16 +292,33 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
LogReply("AddItem", addItemReply);
Assert.Equal(ProtocolStatusCode.Ok, addItemReply.ProtocolStatus.Code);
Assert.True(addItemReply.AddItem.ItemHandle > 0);
+ serverHandle = registerReply.Register.ServerHandle;
+ itemHandle = addItemReply.AddItem.ItemHandle;
+ // Supervisory, not plain, advise: MXAccess refuses a user-id-0 write on a
+ // plainly advised item with SecurityError/1008. Proven on the DEV gateway
+ // (wonder-app-vd03, 2026-11-12, #212): on MESReceiver_025.MoveInBatchID, Write2
+ // applied the value after AdviseSupervisory and got SecurityError/1008 after Advise.
MxCommandReply adviseReply = await fixture.Service.Invoke(
- CreateAdviseRequest(
+ CreateAdviseSupervisoryRequest(
sessionId,
registerReply.Register.ServerHandle,
addItemReply.AddItem.ItemHandle),
new TestServerCallContext()).ConfigureAwait(false);
- LogReply("Advise", adviseReply);
+ LogReply("AdviseSupervisory", adviseReply);
Assert.Equal(ProtocolStatusCode.Ok, adviseReply.ProtocolStatus.Code);
+ // The write below can now really apply, so remember the value to restore.
+ MxEvent initialValue = await eventWriter
+ .WaitForMessageAsync(
+ candidate => candidate.Family == MxEventFamily.OnDataChange
+ && candidate.ItemHandle == addItemReply.AddItem.ItemHandle,
+ IntegrationTestEnvironment.LiveMxAccessEventTimeout,
+ streamCancellation.Token)
+ .ConfigureAwait(false);
+ LogEvent(initialValue);
+ originalValue = initialValue.Value;
+
MxCommandReply writeReply = await fixture.Service.Invoke(
CreateWrite2Request(
sessionId,
@@ -308,11 +329,10 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
// Ok means the worker reached the COM Write2 call and COM accepted it.
// InvalidRequest here means the executor rejected the payload
- // (missing value/timestamp) before reaching MXAccess. Ok does not
- // mean the provider applied the value: on the windev Galaxy the
- // default item is security-classified, so the completion carries
- // SecurityError/1008 (an unauthenticated write refused; Write2 has
- // no user id). Plain Write gets the same status (#212, 2026-11-12).
+ // (missing value/timestamp) before reaching MXAccess. Ok alone does
+ // not mean the provider applied the value; the completion status
+ // below carries that. (The 2026-11-12 windev run used a plain Advise
+ // and got SecurityError/1008 on the completion; see #212.)
Assert.Equal(ProtocolStatusCode.Ok, writeReply.ProtocolStatus.Code);
Assert.Equal(MxCommandKind.Write2, writeReply.Kind);
@@ -337,6 +357,23 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
Assert.Equal(registerReply.Register.ServerHandle, writeComplete.ServerHandle);
Assert.Equal(addItemReply.AddItem.ItemHandle, writeComplete.ItemHandle);
+ foreach (MxStatusProxy status in writeComplete.Statuses)
+ {
+ output.WriteLine($"Write2 completion category={status.Category} detail={status.Detail}");
+ }
+
+ // Restore the original value with a plain Write on the same supervisory advise.
+ MxCommandReply restoreReply = await fixture.Service.Invoke(
+ CreateWriteRequest(
+ sessionId,
+ registerReply.Register.ServerHandle,
+ addItemReply.AddItem.ItemHandle,
+ originalValue),
+ new TestServerCallContext()).ConfigureAwait(false);
+ LogReply("Write (restore)", restoreReply);
+ Assert.Equal(ProtocolStatusCode.Ok, restoreReply.ProtocolStatus.Code);
+ restored = true;
+
// The stream task must not be in a faulted state. ShutDownAsync's
// broad catch would otherwise swallow the fault and silently let
// this Write2-parity coverage pass against a broken event pipeline.
@@ -346,6 +383,23 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
}
finally
{
+ if (!restored && originalValue is not null && sessionId is not null && itemHandle != 0)
+ {
+ // Best effort: do not leave the Write2 test value behind after a failed
+ // assertion. Logged, not thrown, so the original failure is not masked.
+ try
+ {
+ MxCommandReply restoreReply = await fixture.Service.Invoke(
+ CreateWriteRequest(sessionId, serverHandle, itemHandle, originalValue),
+ new TestServerCallContext()).ConfigureAwait(false);
+ LogReply("Write (restore after failure)", restoreReply);
+ }
+ catch (Exception ex)
+ {
+ output.WriteLine($"Restore after failure threw {ex.GetType().Name}: {ex.Message}");
+ }
+ }
+
// Cancel the stream call before draining so StreamEvents observes
// cancellation rather than blocking on the channel. Any unhandled
// stream-task fault is rethrown from ShutDownAsync into the test.
@@ -1539,6 +1593,50 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
};
}
+ private static MxCommandRequest CreateAdviseSupervisoryRequest(
+ string sessionId,
+ int serverHandle,
+ int itemHandle)
+ {
+ return new MxCommandRequest
+ {
+ SessionId = sessionId,
+ ClientCorrelationId = "live-advise-supervisory",
+ Command = new MxCommand
+ {
+ Kind = MxCommandKind.AdviseSupervisory,
+ AdviseSupervisory = new AdviseSupervisoryCommand
+ {
+ ServerHandle = serverHandle,
+ ItemHandle = itemHandle,
+ },
+ },
+ };
+ }
+
+ private static MxCommandRequest CreateWriteRequest(
+ string sessionId,
+ int serverHandle,
+ int itemHandle,
+ MxValue value)
+ {
+ return new MxCommandRequest
+ {
+ SessionId = sessionId,
+ ClientCorrelationId = "live-write-restore",
+ Command = new MxCommand
+ {
+ Kind = MxCommandKind.Write,
+ Write = new WriteCommand
+ {
+ ServerHandle = serverHandle,
+ ItemHandle = itemHandle,
+ Value = value,
+ },
+ },
+ };
+ }
+
private static MxCommandRequest CreateWriteRequest(
string sessionId,
int serverHandle,