test(live): prove Write2 applies a value via supervisory advise on DEV (#212)
ci / nightly-windev (push) Has been skipped
ci / portable (push) Failing after 7m54s
ci / windows-x86 (push) Failing after 10m16s
ci / java (push) Failing after 10m17s

On the DEV gateway (wonder-app-vd03, 2b13564e), Write2 after
AdviseSupervisory applied the value to MESReceiver_025.MoveInBatchID
(0 -> 212212, OnWriteComplete Ok), and the value was restored to 0. After a
plain Advise, the same Write2 got SecurityError/1008, which is exactly what
the windev run saw. So that refusal came from the plain advise. It does not
show that windev has no writable attribute.

- Client.Tests: add the opt-in LiveGatewayWrite2Tests (gated by
  LiveGatewayWriteFact: endpoint, key file and write item env vars). It runs
  supervisory advise -> Write2 -> readback -> restore. The value test passed
  live on vd03. The timestamp-parity test needs a second opt-in; it fails on
  a non-UTC host until #228 is fixed.
- IntegrationTests: the windev Write2 smoke now uses AdviseSupervisory and
  restores the original value. It has not been re-run on windev.
- GatewayTesting.md: document the env vars. code-reviews IntegrationTests-033:
  correct the "no writable attribute" limit.

The run also found that the Write2 timestamp is read as host-local time
(stored +5 h on the UTC-5 box); filed as #228.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
Joseph Doherty
2026-11-12 20:40:46 -05:00
parent ebbfaa4c03
commit 7481b95905
5 changed files with 406 additions and 9 deletions
@@ -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;
/// <summary>
/// Live proof that <c>Write2</c> applies a value and timestamp through a real gateway (#212).
/// The item is advised <b>supervisory</b> 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 <c>Write</c> before the test returns.
/// </summary>
public sealed class LiveGatewayWrite2Tests(ITestOutputHelper output)
{
private static readonly TimeSpan EventTimeout = TimeSpan.FromSeconds(20);
/// <summary>Write2 on a supervisory-advised item applies the value; the original is restored.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[LiveGatewayWriteFact]
public async Task Write2_SupervisoryAdvise_AppliesValue()
{
Write2Outcome outcome = await RunWrite2RoundTripAsync();
Assert.Equal(outcome.WrittenValue, outcome.ObservedValue);
Assert.Equal(outcome.OriginalValue, outcome.RestoredValue);
}
/// <summary>
/// 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).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<Write2Outcome> 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<MxEvent> events = Channel.CreateUnbounded<MxEvent>();
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<MxEvent> WaitForAsync(Channel<MxEvent> 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;
}
}
}
/// <summary>Waits for the OnDataChange and OnWriteComplete a write raises, in either order.</summary>
private static async Task<(MxEvent DataChange, MxEvent Completion)> WaitForWriteAsync(Channel<MxEvent> 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);
}
@@ -0,0 +1,57 @@
namespace ZB.MOM.WW.MxGateway.Client.Tests;
/// <summary>
/// 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 <c>docs/GatewayTesting.md</c>, "Live gateway write".
/// </summary>
public sealed class LiveGatewayWriteFactAttribute : FactAttribute
{
/// <summary>Gateway gRPC endpoint, e.g. <c>http://host:5120</c>.</summary>
public const string EndpointVariableName = "MXGATEWAY_LIVE_GATEWAY_ENDPOINT";
/// <summary>API key (<c>mxgw_&lt;id&gt;_&lt;secret&gt;</c>). Prefer the file variant so the key stays out of the environment.</summary>
public const string ApiKeyVariableName = "MXGATEWAY_LIVE_GATEWAY_API_KEY";
/// <summary>Path to a file holding the API key. Takes precedence over <see cref="ApiKeyVariableName"/>.</summary>
public const string ApiKeyFileVariableName = "MXGATEWAY_LIVE_GATEWAY_API_KEY_FILE";
/// <summary>A writable, test-only Int32 attribute. It is written and then restored. No default on purpose.</summary>
public const string WriteItemVariableName = "MXGATEWAY_LIVE_GATEWAY_WRITE_ITEM";
/// <summary>Set to <c>1</c> to also run the Write2 timestamp-parity test (fails on a non-UTC host until #228 is fixed).</summary>
public const string AssertWrite2TimestampVariableName = "MXGATEWAY_LIVE_GATEWAY_ASSERT_WRITE2_TIMESTAMP";
/// <summary>Initializes the attribute, skipping unless the live gateway write variables are set.</summary>
/// <param name="requireTimestampOptIn">When true, also require <see cref="AssertWrite2TimestampVariableName"/>=1.</param>
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();
}
}
}
@@ -716,3 +716,5 @@ The prior `DashboardAuthenticator` ctor took `IOptions<GatewayOptions>`, 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.
+39 -2
View File
@@ -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://<host>: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
@@ -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,