diff --git a/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs b/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs
index 392bf85f..1885dc1f 100644
--- a/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs
@@ -647,6 +647,197 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
}
}
+ ///
+ /// Issue #238 live repro: a ReadBulk of a tag the client already holds must not
+ /// tear down the client's item or subscription. Step 1 reads an added-but-not-advised
+ /// item (deterministic: it is never cached), after which the client must still be able
+ /// to advise its own handle. Step 2 reads the tag right after that advise — the window a
+ /// subscribe-then-seed-read client hits, where the first OnDataChange may not be cached
+ /// yet — and then proves the subscription still delivers by writing a fresh value and
+ /// waiting for its OnDataChange. Before the fix, either read could unadvise and remove
+ /// the client's item, so the advise failed or the written value never arrived.
+ ///
+ /// A task that represents the asynchronous operation.
+ [LiveMxAccessFact]
+ public async Task GatewaySession_WithLiveWorker_ReadBulkOfClientHeldTag_LeavesTheClientSubscriptionLive()
+ {
+ string workerExecutablePath = IntegrationTestEnvironment.ResolveLiveMxAccessWorkerExecutablePath();
+ Assert.True(
+ File.Exists(workerExecutablePath),
+ $"Live MXAccess worker executable was not found at {workerExecutablePath}. Build the worker or set {IntegrationTestEnvironment.LiveMxAccessWorkerExecutableVariableName}.");
+
+ TestWorkerProcessFactory processFactory = new(output);
+ await using GatewayServiceFixture fixture = new(workerExecutablePath, processFactory, output);
+ using RecordingServerStreamWriter eventWriter = new();
+
+ string? sessionId = null;
+ Task? streamTask = null;
+ int serverHandle = 0;
+ int itemHandle = 0;
+ MxValue? originalValue = null;
+ bool restored = false;
+ using CancellationTokenSource streamCancellation = new();
+
+ try
+ {
+ OpenSessionReply openReply = await fixture.Service.OpenSession(
+ new OpenSessionRequest
+ {
+ ClientSessionName = "live-mxaccess-readbulk-held",
+ ClientCorrelationId = "live-open-readbulk-held",
+ CommandTimeout = Duration.FromTimeSpan(CommandTimeout),
+ },
+ new TestServerCallContext()).ConfigureAwait(false);
+
+ sessionId = openReply.SessionId;
+ Assert.Equal(ProtocolStatusCode.Ok, openReply.ProtocolStatus.Code);
+
+ streamTask = fixture.Service.StreamEvents(
+ new StreamEventsRequest { SessionId = sessionId },
+ eventWriter,
+ new TestServerCallContext(streamCancellation.Token));
+
+ MxCommandReply registerReply = await fixture.Service.Invoke(
+ CreateRegisterRequest(sessionId),
+ new TestServerCallContext()).ConfigureAwait(false);
+ LogReply("Register", registerReply);
+ Assert.Equal(ProtocolStatusCode.Ok, registerReply.ProtocolStatus.Code);
+ serverHandle = registerReply.Register.ServerHandle;
+
+ MxCommandReply addItemReply = await fixture.Service.Invoke(
+ CreateAddItemRequest(sessionId, serverHandle),
+ new TestServerCallContext()).ConfigureAwait(false);
+ LogReply("AddItem", addItemReply);
+ Assert.Equal(ProtocolStatusCode.Ok, addItemReply.ProtocolStatus.Code);
+ itemHandle = addItemReply.AddItem.ItemHandle;
+
+ // Step 1: added but not advised.
+ BulkReadResult addedOnlyRead = await ReadBulkSingleAsync(fixture, sessionId, serverHandle, "added-only").ConfigureAwait(false);
+ Assert.True(addedOnlyRead.WasSuccessful, addedOnlyRead.ErrorMessage);
+ Assert.Equal(itemHandle, addedOnlyRead.ItemHandle);
+ originalValue = addedOnlyRead.Value;
+ ulong sequenceAfterFirstRead = LastWorkerSequence(eventWriter);
+
+ // Supervisory so the user-id-0 write in step 2 applies (#212). This fails with an
+ // invalid-handle MXAccess status if the read removed the client's item.
+ MxCommandReply adviseReply = await fixture.Service.Invoke(
+ CreateAdviseSupervisoryRequest(sessionId, serverHandle, itemHandle),
+ new TestServerCallContext()).ConfigureAwait(false);
+ LogReply("AdviseSupervisory", adviseReply);
+ Assert.Equal(ProtocolStatusCode.Ok, adviseReply.ProtocolStatus.Code);
+
+ // Step 2: advised, read immediately (cached or not, depending on the race with the
+ // first OnDataChange — logged so a run shows which path it exercised).
+ BulkReadResult advisedRead = await ReadBulkSingleAsync(fixture, sessionId, serverHandle, "advised").ConfigureAwait(false);
+ Assert.True(advisedRead.WasSuccessful, advisedRead.ErrorMessage);
+ Assert.Equal(itemHandle, advisedRead.ItemHandle);
+
+ MxEvent firstAdvisedChange = await eventWriter
+ .WaitForMessageAsync(
+ candidate => candidate.Family == MxEventFamily.OnDataChange
+ && candidate.ItemHandle == itemHandle
+ && candidate.WorkerSequence > sequenceAfterFirstRead,
+ IntegrationTestEnvironment.LiveMxAccessEventTimeout,
+ streamCancellation.Token)
+ .ConfigureAwait(false);
+ LogEvent(firstAdvisedChange);
+
+ int freshValue = originalValue is { DataType: MxDataType.Integer }
+ ? unchecked(originalValue.Int32Value + 1)
+ : 238;
+ MxCommandReply writeReply = await fixture.Service.Invoke(
+ CreateWriteRequest(
+ sessionId,
+ serverHandle,
+ itemHandle,
+ new MxValue { DataType = MxDataType.Integer, Int32Value = freshValue }),
+ new TestServerCallContext()).ConfigureAwait(false);
+ LogReply("Write", writeReply);
+ Assert.Equal(ProtocolStatusCode.Ok, writeReply.ProtocolStatus.Code);
+
+ MxEvent writtenChange = await eventWriter
+ .WaitForMessageAsync(
+ candidate => candidate.Family == MxEventFamily.OnDataChange
+ && candidate.ItemHandle == itemHandle
+ && candidate.Value is { DataType: MxDataType.Integer } value
+ && value.Int32Value == freshValue,
+ IntegrationTestEnvironment.LiveMxAccessEventTimeout,
+ streamCancellation.Token)
+ .ConfigureAwait(false);
+ LogEvent(writtenChange);
+
+ if (originalValue is not null)
+ {
+ MxCommandReply restoreReply = await fixture.Service.Invoke(
+ CreateWriteRequest(sessionId, serverHandle, itemHandle, originalValue),
+ new TestServerCallContext()).ConfigureAwait(false);
+ LogReply("Write (restore)", restoreReply);
+ restored = true;
+ }
+
+ Assert.False(
+ streamTask.IsFaulted,
+ streamTask.Exception?.ToString() ?? "Event stream task faulted without an exception.");
+ }
+ finally
+ {
+ if (!restored && originalValue is not null && sessionId is not null && itemHandle != 0)
+ {
+ 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}");
+ }
+ }
+
+ streamCancellation.Cancel();
+ await ShutDownAsync(fixture, processFactory, sessionId, streamTask, propagateStreamFaults: true).ConfigureAwait(false);
+ }
+ }
+
+ private async Task ReadBulkSingleAsync(
+ GatewayServiceFixture fixture,
+ string sessionId,
+ int serverHandle,
+ string label)
+ {
+ MxCommandReply reply = await fixture.Service.Invoke(
+ new MxCommandRequest
+ {
+ SessionId = sessionId,
+ ClientCorrelationId = "live-read-bulk-" + label,
+ Command = new MxCommand
+ {
+ Kind = MxCommandKind.ReadBulk,
+ ReadBulk = new ReadBulkCommand
+ {
+ ServerHandle = serverHandle,
+ TagAddresses = { IntegrationTestEnvironment.LiveMxAccessItem },
+ TimeoutMs = 5000,
+ },
+ },
+ },
+ new TestServerCallContext()).ConfigureAwait(false);
+ LogReply("ReadBulk(" + label + ")", reply);
+ Assert.Equal(ProtocolStatusCode.Ok, reply.ProtocolStatus.Code);
+ BulkReadResult result = Assert.Single(reply.ReadBulk.Results);
+ output.WriteLine(
+ $"ReadBulk({label}) success={result.WasSuccessful} cached={result.WasCached} item_handle={result.ItemHandle} error={result.ErrorMessage}");
+ return result;
+ }
+
+ private static ulong LastWorkerSequence(RecordingServerStreamWriter eventWriter)
+ {
+ IReadOnlyList messages = eventWriter.Messages;
+ return messages.Count == 0 ? 0UL : messages.Max(message => message.WorkerSequence);
+ }
+
///
/// Verifies the MXAccess WriteSecured path: AuthenticateUser resolves a
/// user id, then WriteSecured against the advised item completes its round-trip