test(integration): live repro for ReadBulk of a client-held tag (#238)
ci / windows-x86 (push) Successful in 1m52s
ci / java (push) Failing after 5m15s
ci / portable (push) Failing after 11m53s

Reads an added-but-not-advised item, then advises it, reads it again in
the subscribe-then-seed-read window, and proves the subscription still
delivers by writing a fresh value and waiting for its OnDataChange.
This commit is contained in:
Joseph Doherty
2026-12-01 19:27:11 -05:00
parent 7a41d9edea
commit 13e9a26d39
@@ -647,6 +647,197 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
}
}
/// <summary>
/// Issue #238 live repro: a <c>ReadBulk</c> 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<MxEvent> 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<BulkReadResult> 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<MxEvent> eventWriter)
{
IReadOnlyList<MxEvent> messages = eventWriter.Messages;
return messages.Count == 0 ? 0UL : messages.Max(message => message.WorkerSequence);
}
/// <summary>
/// Verifies the MXAccess <c>WriteSecured</c> path: <c>AuthenticateUser</c> resolves a
/// user id, then <c>WriteSecured</c> against the advised item completes its round-trip