4 Commits

Author SHA1 Message Date
Joseph Doherty cc33b063fa fix(worker): leave added-only caller items to a snapshot AddItem (#238)
ci / windows-x86 (push) Successful in 2m4s
ci / java (push) Failing after 6m50s
ci / portable (push) Failing after 9m33s
The live run on windev showed MXAccess hands a re-added address a new
handle, so reading a caller's added-but-not-advised item through the
caller's handle (temporary Advise/UnAdvise) touched the caller's item for
no reason. Only an advised-but-uncached caller tag now reuses the caller's
handle (waiting on its existing subscription). Every other tag takes a
snapshot AddItem; if that AddItem returns a handle the registry already
tracks, it is still treated as the caller's item and never removed.

Docs and tests updated to the live observation; the live test now logs
the snapshot handle MXAccess returned for the re-added address.
2026-12-01 19:38:11 -05:00
Joseph Doherty 2e6645ef92 fix(worker): UnAdvise evicts the item's cached value (#238)
ci / windows-x86 (push) Successful in 1m51s
ci / java (push) Failing after 7m13s
ci / portable (push) Failing after 14m3s
The live repro showed the value a ReadBulk's temporary advice on a
caller's added-only item captured surviving the UnAdvise, so after the
caller advised the item ReadBulk answered was_cached=true with that value
before the caller's own first OnDataChange. The same staleness applied to
any client UnAdvise followed by a re-advise. Drop the entry on UnAdvise;
the item stays added.
2026-12-01 19:31:49 -05:00
Joseph Doherty 13e9a26d39 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.
2026-12-01 19:27:11 -05:00
Joseph Doherty 7a41d9edea fix(worker): ReadBulk never tears down a caller's item or subscription (#238)
ReadBulk sent every advised-but-uncached and added-but-not-advised tag
down the snapshot path. MXAccess returns the caller's existing handle for
a re-added address, so the snapshot's AddItem/Advise ran on the caller's
own item and the symmetric teardown then UnAdvised and RemoveItem'd it:
the subscription delivered one value and went silent.

Teardown is now ownership-scoped: it unadvises only advices the read's
own Advise created and removes only items the read's own AddItem created.
A tag the session already holds is read through the caller's handle with
no AddItem: advised-but-uncached waits on the existing subscription with
no COM call; added-but-not-advised is advised for the read and unadvised
afterwards (back to its prior state), never removed. A snapshot AddItem
that returns a handle the registry already tracks (differently spelled
address) is treated as the caller's item and never removed.

Adds MxAccessSessionTests regressions; updates gateway.md, Contracts,
DesignDecisions, MxAccessWorkerInstanceDesign.
2026-12-01 19:25:19 -05:00
9 changed files with 829 additions and 78 deletions
+5 -3
View File
@@ -88,9 +88,11 @@ of items per round trip while preserving MXAccess parity per entry.
`was_successful`, `was_cached`, `value`, `quality`, `source_timestamp`, `was_successful`, `was_cached`, `value`, `quality`, `source_timestamp`,
`repeated MxStatusProxy statuses`, and `error_message`. MXAccess has no `repeated MxStatusProxy statuses`, and `error_message`. MXAccess has no
synchronous `Read`, so `ReadBulk` is dual-mode per entry: when a tag is synchronous `Read`, so `ReadBulk` is dual-mode per entry: when a tag is
already advised in the session the worker returns the cached already advised in the session and has a cached value the worker returns
`OnDataChange` payload without touching the subscription the cached `OnDataChange` payload without touching the subscription
(`was_cached = true`); otherwise the worker takes a full (`was_cached = true`); a tag the session has advised without a cached
value yet is read by waiting on that existing subscription; otherwise the
worker takes a full
`AddItem` + `Advise` + wait-for-first-`OnDataChange` + `UnAdvise` + `AddItem` + `Advise` + wait-for-first-`OnDataChange` + `UnAdvise` +
`RemoveItem` snapshot lifecycle and returns the result `RemoveItem` snapshot lifecycle and returns the result
(`was_cached = false`). The asymmetry that `BulkReadResult` has no (`was_cached = false`). The asymmetry that `BulkReadResult` has no
+25 -6
View File
@@ -532,7 +532,23 @@ choices were considered:
(`was_cached = true`). Otherwise it takes the full `AddItem + Advise + (`was_cached = true`). Otherwise it takes the full `AddItem + Advise +
wait-for-first-OnDataChange + UnAdvise + RemoveItem` lifecycle itself wait-for-first-OnDataChange + UnAdvise + RemoveItem` lifecycle itself
(`was_cached = false`) and leaves the session exactly as it was before (`was_cached = false`) and leaves the session exactly as it was before
the call. The cache lives on a per-session `MxAccessValueCache`, the call. "Exactly as it was" is enforced by ownership, not by
symmetry: teardown undoes only the `AddItem` and `Advise` calls the read
itself made (#238). An advised tag whose first `OnDataChange` is not
cached yet is read by waiting on the caller's own subscription, with no
`AddItem` at all. Any other tag gets a snapshot `AddItem`. The installed
MXAccess on windev hands a re-added address a new handle (observed
2026-12-01), so a caller's added-but-not-advised item is not touched and
the snapshot item is torn down on its own. The worker does not rely on
that: when the snapshot `AddItem` returns a handle the registry already
tracks, the handle is the caller's, and a symmetric teardown would
unadvise and remove the caller's item — a subscription that delivered
one value and went silent. Such a handle is advised for the read only
if nothing advises it yet, unadvised afterwards (back to the caller's
added-not-advised state), and never removed; at worst one extra
`AddItem` reference outlives the read until the caller removes the item
or unregisters, which is preferable to deleting a live subscription.
The cache lives on a per-session `MxAccessValueCache`,
populated by `MxAccessBaseEventSink` on every `OnDataChange` after the populated by `MxAccessBaseEventSink` on every `OnDataChange` after the
event clears the outbound queue. event clears the outbound queue.
@@ -543,12 +559,15 @@ choices were considered:
The chosen behavior matches what callers actually want from "current The chosen behavior matches what callers actually want from "current
value" — a free read of an already-streaming tag, and a one-shot snapshot value" — a free read of an already-streaming tag, and a one-shot snapshot
otherwise — and never disturbs subscriptions the caller did not create. otherwise — and never disturbs subscriptions the caller already holds.
The decision intentionally does NOT synthesize an `OnDataChange` event The decision intentionally does NOT synthesize an `OnDataChange` event
from the snapshot path: the snapshot value reaches the caller through from the snapshot path: the worker adds no event of its own for the
`ReadBulk`'s reply payload only, not through the event stream. This snapshot value, which reaches the caller through `ReadBulk`'s reply
preserves the "Don't synthesize events" rule that scopes the rest of the payload. The native `OnDataChange` MXAccess raises for a handle the read
worker. advised still flows through the event sink like any other (under the
snapshot item handle, or under the caller's own handle in the fallback
above where `AddItem` returned it). This preserves the "Don't
synthesize events" rule that scopes the rest of the worker.
`ReadBulk`'s wait loop pumps Windows messages on the worker STA `ReadBulk`'s wait loop pumps Windows messages on the worker STA
(`StaRuntime.PumpPendingMessages`) on every poll iteration so the inbound (`StaRuntime.PumpPendingMessages`) on every poll iteration so the inbound
+21 -5
View File
@@ -355,10 +355,21 @@ timeout.
`ReadBulk` runs its snapshot lifecycle in phases so the STA is held for at most `ReadBulk` runs its snapshot lifecycle in phases so the STA is held for at most
one `timeout_ms` per command, not one per tag: (1) every tag is validated and one `timeout_ms` per command, not one per tag: (1) every tag is validated and
probed against the cached-and-advised fast path; (2) every remaining tag is probed against the registry and the cached-and-advised fast path; (2) every
added and advised; (3) one wait with a shared deadline collects the first remaining tag gets an advised handle — a tag the caller has advised keeps the
`OnDataChange` per snapshot handle and returns as soon as all have delivered; caller's item handle and its existing subscription, any other tag gets the
(4) every snapshot handle is unadvised and removed, best-effort. Per-tag read's own `AddItem`, and a handle is advised only when nothing advises it
yet; (3) one wait with a shared deadline collects the first `OnDataChange` per
handle and returns as soon as all have delivered; (4) teardown, best-effort
and ownership-scoped, unadvises only the advices phase 2 created and removes
only the items phase 2 added. The caller's items are therefore never removed
and the caller's subscriptions never unadvised (#238). A snapshot `AddItem`
that returns a handle the registry already tracks is the caller's item: it is
advised for the read only if nothing advises it yet, unadvised afterwards,
and never removed. (The windev MXAccess install returns a new handle for a
re-added address, so in practice an added-only caller item is not touched;
the ownership check covers an install or address spelling that resolves to
the caller's handle.) Per-tag
results are unchanged: request order, the blank-address failure, the cached results are unchanged: request order, the blank-address failure, the cached
result, an `AddItem` failure (item handle 0) or `Advise` failure (its own item result, an `AddItem` failure (item handle 0) or `Advise` failure (its own item
handle) failing only that tag, and the `ReadBulk timed out after <n> ms waiting handle) failing only that tag, and the `ReadBulk timed out after <n> ms waiting
@@ -737,7 +748,12 @@ the handle they receive when the registry does not already track it. An
`Unregister` ran is dispatched after the eviction and recreates the entry; `Unregister` ran is dispatched after the eviction and recreates the entry;
when MXAccess later reuses that item id, `ReadBulk`'s cached path would when MXAccess later reuses that item id, `ReadBulk`'s cached path would
otherwise serve the stale value as `was_cached = true`. A handle the otherwise serve the stale value as `was_cached = true`. A handle the
registry still tracks belongs to a live item, so its entries are kept. Failed advice and cleanup calls registry still tracks belongs to a live item, so its entries are kept.
Successful `UnAdvise` drops the handle pair's `MxAccessValueCache` entry too:
the item stays added, but its value stops updating, so without the eviction a
later re-advise would let `ReadBulk`'s cached path answer with the previous
advice's value (including one a `ReadBulk`'s temporary advice on a caller's
handle captured) before the new advice's first `OnDataChange` lands. Failed advice and cleanup calls
leave registry state unchanged so diagnostics continue to reflect the last leave registry state unchanged so diagnostics continue to reflect the last
successful MXAccess-owned state transition. successful MXAccess-owned state transition.
+11 -4
View File
@@ -570,11 +570,18 @@ returns one result per requested entry — per-entry failures populate
last cached `OnDataChange` payload when the requested tag is already last cached `OnDataChange` payload when the requested tag is already
advised (`was_cached = true`, no subscription side-effects), or by advised (`was_cached = true`, no subscription side-effects), or by
taking a full `AddItem` + `Advise` + wait-for-first-OnDataChange + taking a full `AddItem` + `Advise` + wait-for-first-OnDataChange +
`UnAdvise` + `RemoveItem` snapshot lifecycle when no live subscription `UnAdvise` + `RemoveItem` snapshot lifecycle otherwise
exists (`was_cached = false`). `timeout_ms` is one shared deadline for (`was_cached = false`). A tag the session has advised whose first
`OnDataChange` is not cached yet is read by waiting on the caller's own
subscription, with no COM call (`was_cached = false`). Teardown only
undoes the `AddItem` and `Advise` calls the read itself made: if a
snapshot `AddItem` returns a handle the session already holds, that
handle is never removed, and is unadvised only if the read advised it,
so a seed read issued right after subscribing cannot cancel the
subscription (#238). `timeout_ms` is one shared deadline for
the whole command, not a per-tag budget: the worker adds and advises the whole command, not a per-tag budget: the worker adds and advises
every uncached tag first, waits once for all of them, then tears them every tag that needs it first, waits once for all of them, then tears
all down, so the STA is held for at most one `timeout_ms` (plus the down its own snapshot state, so the STA is held for at most one `timeout_ms` (plus the
add/advise and teardown COM calls, during which it pumps every 16 tags). add/advise and teardown COM calls, during which it pumps every 16 tags).
Each tag that has not delivered by the deadline surfaces its own Each tag that has not delivered by the deadline surfaces its own
`was_successful = false` timeout rather than throwing. Duplicate `was_successful = false` timeout rather than throwing. Duplicate
@@ -647,6 +647,200 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
} }
} }
/// <summary>
/// Issue #238: 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, 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 must read through the client's own handle
/// rather than a snapshot item; the test then proves the subscription still delivers by
/// writing a fresh value and waiting for its OnDataChange. The step 1 snapshot handle is
/// logged: on the windev install (2026-12-01) MXAccess returned a new handle for the
/// re-added address, so the pre-fix worker's teardown never reached the client's item
/// there; only the step 2 handle assertion distinguishes the fixed worker.
/// </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);
output.WriteLine(
$"Snapshot AddItem for a client-held address returned {(addedOnlyRead.ItemHandle == itemHandle ? "the client's handle" : "a new handle")} ({addedOnlyRead.ItemHandle} vs client {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> /// <summary>
/// Verifies the MXAccess <c>WriteSecured</c> path: <c>AuthenticateUser</c> resolves a /// 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 /// user id, then <c>WriteSecured</c> against the advised item completes its round-trip
@@ -715,8 +715,8 @@ public sealed class MxAccessCommandExecutorTests
new ZB.MOM.WW.MxGateway.Worker.Conversion.VariantConverter()); new ZB.MOM.WW.MxGateway.Worker.Conversion.VariantConverter());
// Registry half of the fast path: the tag must resolve to a live item // Registry half of the fast path: the tag must resolve to a live item
// handle on this server AND carry an advice, or TryGetCachedReadFor // handle on this server AND carry an advice and a cached value, or
// falls through to the AddItem/Advise snapshot lifecycle. // FindExistingItem sends the tag to the wait/snapshot path.
MxCommandReply registerReply = executor.Execute( MxCommandReply registerReply = executor.Execute(
CreateRegisterCommand("register-before-cached-read", "client-a")); CreateRegisterCommand("register-before-cached-read", "client-a"));
MxCommandReply addItemReply = executor.Execute( MxCommandReply addItemReply = executor.Execute(
@@ -257,11 +257,11 @@ public sealed class MxAccessHandleRegistryTests
} }
/// <summary> /// <summary>
/// Pins the registry half of <c>MxAccessSession.TryGetCachedReadFor</c>'s fall-through /// Pins the registry half of <c>MxAccessSession.FindExistingItem</c>'s cached-read
/// contract. That scan walks <see cref="MxAccessHandleRegistry.GetItemHandlesForDefinition"/> /// contract. That scan walks <see cref="MxAccessHandleRegistry.GetItemHandlesForDefinition"/>
/// in order and skips any candidate carrying neither a plain nor a supervisory advice, /// in order and never serves the cache of a candidate carrying neither a plain nor a
/// because an added-but-unadvised item will never receive a fresh <c>OnDataChange</c> and so /// supervisory advice, because an added-but-unadvised item will never receive a fresh
/// can only serve a stale cache entry. The registry has to make that skip possible: the /// <c>OnDataChange</c> and so can only serve a stale cache entry. The registry has to make that skip possible: the
/// duplicate registrations of one tag must come back in a stable ascending order, and the /// duplicate registrations of one tag must come back in a stable ascending order, and the
/// advice index must answer per item handle rather than per tag. Asserted here rather than /// advice index must answer per item handle rather than per tag. Asserted here rather than
/// on the session because the session's read path needs a live MXAccess COM instance. /// on the session because the session's read path needs a live MXAccess COM instance.
@@ -428,6 +428,343 @@ public sealed class MxAccessSessionTests
Assert.Contains(pumpAtOperation, at => at > firstUnAdvise); Assert.Contains(pumpAtOperation, at => at > firstUnAdvise);
} }
/// <summary>
/// Issue #238: a tag the caller has added and advised whose first
/// OnDataChange has not been cached yet must be read through the
/// caller's own subscription. The read makes no AddItem, Advise,
/// UnAdvise, or RemoveItem call, and the caller's item and advice
/// survive it. The fake reuses the handle for a re-added address, so
/// the pre-fix snapshot path would have torn down the caller's item.
/// </summary>
[Fact]
public void ReadBulk_AdvisedTagWithNoCachedValue_WaitsOnTheCallersSubscriptionWithoutTearingItDown()
{
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int callerHandle = session.AddItem(serverHandle, "Tag.Subscribed");
session.Advise(serverHandle, callerHandle);
int operationsBeforeRead = server.Operations.Count;
// The caller's subscription delivers its first OnDataChange mid-wait.
Action pumpStep = () =>
{
if (!valueCache.TryGet(serverHandle, callerHandle, out _))
{
valueCache.Set(serverHandle, callerHandle, BuildDataChange(serverHandle, callerHandle, 61));
}
};
BulkReadResult result = Assert.Single(
session.ReadBulk(serverHandle, new[] { "Tag.Subscribed" }, TimeSpan.FromSeconds(5), pumpStep));
Assert.True(result.WasSuccessful);
Assert.False(result.WasCached);
Assert.Equal(callerHandle, result.ItemHandle);
Assert.Equal(61, result.Value.Int32Value);
Assert.Empty(server.Operations.Skip(operationsBeforeRead));
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.Subscribed", expectAdvised: true);
}
/// <summary>
/// The same advised-but-uncached tag that never delivers within the
/// timeout reports its own timeout and still leaves the caller's
/// subscription alone.
/// </summary>
[Fact]
public void ReadBulk_AdvisedTagThatNeverDelivers_TimesOutWithoutTearingDownTheCallersSubscription()
{
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink());
int serverHandle = session.Register("client");
int callerHandle = session.AddItem(serverHandle, "Tag.Quiet");
session.AdviseSupervisory(serverHandle, callerHandle);
int operationsBeforeRead = server.Operations.Count;
BulkReadResult result = Assert.Single(
session.ReadBulk(serverHandle, new[] { "Tag.Quiet" }, TimeSpan.FromMilliseconds(60), () => { }));
Assert.False(result.WasSuccessful);
Assert.Equal(callerHandle, result.ItemHandle);
Assert.Contains(ReadBulkTimeoutText, result.ErrorMessage, StringComparison.OrdinalIgnoreCase);
Assert.Empty(server.Operations.Skip(operationsBeforeRead));
Assert.True(session.HandleRegistry.ContainsAdviceHandle(serverHandle, callerHandle, MxAccessAdviceKind.Supervisory));
Assert.True(session.HandleRegistry.ContainsItemHandle(serverHandle, callerHandle));
}
/// <summary>
/// A tag the caller has added but not advised takes a snapshot AddItem.
/// The installed MXAccess hands that AddItem a new handle (observed
/// live on windev), so the snapshot item is advised, read, and torn
/// down on its own and the caller's item sees no call at all.
/// </summary>
[Fact]
public void ReadBulk_AddedButNotAdvisedTag_WhenAddItemReturnsANewHandle_LeavesTheCallersItemUntouched()
{
RecordingMxAccessServer server = new();
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int callerHandle = session.AddItem(serverHandle, "Tag.AddedOnly");
int operationsBeforeRead = server.Operations.Count;
Action pumpStep = () =>
{
if (server.TryGetAdvisedHandle("Tag.AddedOnly", out int handle) && !valueCache.TryGet(serverHandle, handle, out _))
{
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, 23));
}
};
BulkReadResult result = Assert.Single(
session.ReadBulk(serverHandle, new[] { "Tag.AddedOnly" }, TimeSpan.FromSeconds(5), pumpStep));
int snapshotHandle = server.HandleForTag("Tag.AddedOnly");
Assert.NotEqual(callerHandle, snapshotHandle);
Assert.True(result.WasSuccessful);
Assert.Equal(snapshotHandle, result.ItemHandle);
Assert.Equal(23, result.Value.Int32Value);
Assert.Equal(
new[]
{
$"AddItem:{serverHandle}:Tag.AddedOnly",
$"Advise:{serverHandle}:{snapshotHandle}",
$"UnAdvise:{serverHandle}:{snapshotHandle}",
$"RemoveItem:{serverHandle}:{snapshotHandle}",
},
server.Operations.Skip(operationsBeforeRead));
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.AddedOnly", expectAdvised: false);
Assert.False(session.HandleRegistry.ContainsItemHandle(serverHandle, snapshotHandle));
}
/// <summary>
/// When the snapshot AddItem for a caller's added-but-not-advised tag
/// returns the caller's own handle, the read advises that handle and
/// unadvises it afterwards — returning the caller's item to its prior
/// added-not-advised state — but never removes it.
/// </summary>
[Fact]
public void ReadBulk_AddedButNotAdvisedTag_WhenAddItemReturnsTheCallersHandle_AdvisesForTheReadButNeverRemovesIt()
{
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int callerHandle = session.AddItem(serverHandle, "Tag.AddedOnly");
int operationsBeforeRead = server.Operations.Count;
Action pumpStep = () =>
{
if (server.TryGetAdvisedHandle("Tag.AddedOnly", out int handle) && !valueCache.TryGet(serverHandle, handle, out _))
{
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, 17));
}
};
BulkReadResult result = Assert.Single(
session.ReadBulk(serverHandle, new[] { "Tag.AddedOnly" }, TimeSpan.FromSeconds(5), pumpStep));
Assert.True(result.WasSuccessful);
Assert.False(result.WasCached);
Assert.Equal(callerHandle, result.ItemHandle);
Assert.Equal(17, result.Value.Int32Value);
Assert.Equal(
new[]
{
$"AddItem:{serverHandle}:Tag.AddedOnly",
$"Advise:{serverHandle}:{callerHandle}",
$"UnAdvise:{serverHandle}:{callerHandle}",
},
server.Operations.Skip(operationsBeforeRead));
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.AddedOnly", expectAdvised: false);
}
/// <summary>
/// UnAdvise drops the item's cached value: the item stays added but the
/// value stops updating, so a later re-advise must not be answered from
/// the previous advice's cache before its own first OnDataChange.
/// </summary>
[Fact]
public void UnAdvise_EvictsTheItemsCachedValueButKeepsTheItem()
{
RecordingMxAccessServer server = new();
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int handle = session.AddItem(serverHandle, "Tag.Readvise");
session.Advise(serverHandle, handle);
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, 3));
session.UnAdvise(serverHandle, handle);
Assert.False(valueCache.TryGet(serverHandle, handle, out _));
Assert.True(session.HandleRegistry.ContainsItemHandle(serverHandle, handle));
}
/// <summary>
/// The value a ReadBulk's temporary advice on a caller's added-only item
/// produced (AddItem returning the caller's handle) must not be served
/// as cached once the caller advises the item itself: the next read
/// waits for the caller's own first value.
/// </summary>
[Fact]
public void ReadBulk_AfterTemporaryAdviceOnAddedOnlyItem_LaterAdviseIsNotServedTheTemporaryValue()
{
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int callerHandle = session.AddItem(serverHandle, "Tag.Seed");
int nextValue = 17;
Action pumpStep = () =>
{
if (server.TryGetAdvisedHandle("Tag.Seed", out int handle) && !valueCache.TryGet(serverHandle, handle, out _))
{
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, nextValue));
}
};
BulkReadResult seed = Assert.Single(
session.ReadBulk(serverHandle, new[] { "Tag.Seed" }, TimeSpan.FromSeconds(5), pumpStep));
Assert.Equal(17, seed.Value.Int32Value);
session.Advise(serverHandle, callerHandle);
nextValue = 99;
BulkReadResult afterAdvise = Assert.Single(
session.ReadBulk(serverHandle, new[] { "Tag.Seed" }, TimeSpan.FromSeconds(5), pumpStep));
Assert.True(afterAdvise.WasSuccessful);
Assert.False(afterAdvise.WasCached);
Assert.Equal(99, afterAdvise.Value.Int32Value);
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.Seed", expectAdvised: true);
}
/// <summary>
/// Defence in depth for the ordinal registry lookup: when a snapshot
/// AddItem for an address the registry does not know comes back with a
/// handle the caller already holds (MXAccess resolving a differently
/// spelled address to the caller's item), the read never removes that
/// item. Advised, it is waited on untouched; added only, it is advised
/// and unadvised for the read. The caller's registration keeps its own
/// item definition.
/// </summary>
/// <param name="callerAdvised">Whether the caller has advised its item.</param>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ReadBulk_SnapshotAddItemReturningACallersHandle_NeverRemovesTheCallersItem(bool callerAdvised)
{
RecordingMxAccessServer server = new();
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int callerHandle = session.AddItem(serverHandle, "Area.Tank.PV");
if (callerAdvised)
{
session.Advise(serverHandle, callerHandle);
}
int operationsBeforeRead = server.Operations.Count;
server.NextItemHandleOverride = callerHandle;
Action pumpStep = () =>
{
if (!valueCache.TryGet(serverHandle, callerHandle, out _))
{
valueCache.Set(serverHandle, callerHandle, BuildDataChange(serverHandle, callerHandle, 5));
}
};
BulkReadResult result = Assert.Single(
session.ReadBulk(serverHandle, new[] { "AREA.TANK.PV" }, TimeSpan.FromSeconds(5), pumpStep));
Assert.True(result.WasSuccessful);
Assert.Equal(callerHandle, result.ItemHandle);
Assert.Equal("AREA.TANK.PV", result.TagAddress);
List<string> readOperations = server.Operations.Skip(operationsBeforeRead).ToList();
Assert.Contains($"AddItem:{serverHandle}:AREA.TANK.PV", readOperations);
Assert.DoesNotContain($"RemoveItem:{serverHandle}:{callerHandle}", readOperations);
Assert.Equal(callerAdvised ? 0 : 1, readOperations.Count(op => op == $"Advise:{serverHandle}:{callerHandle}"));
Assert.Equal(callerAdvised ? 0 : 1, readOperations.Count(op => op == $"UnAdvise:{serverHandle}:{callerHandle}"));
AssertCallerItemIntact(session, serverHandle, callerHandle, "Area.Tank.PV", expectAdvised: callerAdvised);
}
/// <summary>
/// The ScadaBridge reconnect shape (subscribe, then seed-read in one
/// batch): cached, advised-but-uncached, added-only, and never-held
/// tags in one request, with a duplicate of the advised tag. Only the
/// never-held tag's own snapshot item is removed; every caller item
/// survives with exactly the advice it had before the read. The fake
/// reuses handles for re-added addresses, the worst case for teardown.
/// </summary>
[Fact]
public void ReadBulk_MixedCallerAndSnapshotTags_TearsDownOnlyItsOwnSnapshotState()
{
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int cached = session.AddItem(serverHandle, "Tag.Cached");
session.Advise(serverHandle, cached);
valueCache.Set(serverHandle, cached, BuildDataChange(serverHandle, cached, 1));
int advised = session.AddItem(serverHandle, "Tag.Advised");
session.Advise(serverHandle, advised);
int addedOnly = session.AddItem(serverHandle, "Tag.AddedOnly");
int operationsBeforeRead = server.Operations.Count;
Action pumpStep = () =>
{
foreach (string tag in new[] { "Tag.Advised", "Tag.AddedOnly", "Tag.Fresh" })
{
if (server.TryGetAdvisedHandle(tag, out int handle) && !valueCache.TryGet(serverHandle, handle, out _))
{
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, handle));
}
}
};
string[] tags = { "Tag.Cached", "Tag.Advised", "Tag.AddedOnly", "Tag.Fresh", "Tag.Advised" };
IReadOnlyList<BulkReadResult> results = session.ReadBulk(serverHandle, tags, TimeSpan.FromSeconds(5), pumpStep);
Assert.All(results, result => Assert.True(result.WasSuccessful, result.TagAddress + ": " + result.ErrorMessage));
Assert.True(results[0].WasCached);
Assert.Equal(advised, results[1].ItemHandle);
Assert.Equal(addedOnly, results[2].ItemHandle);
Assert.Equal(advised, results[4].ItemHandle);
int fresh = server.HandleForTag("Tag.Fresh");
Assert.Equal(fresh, results[3].ItemHandle);
List<string> readOperations = server.Operations.Skip(operationsBeforeRead).ToList();
Assert.Equal(
new[]
{
$"AddItem:{serverHandle}:Tag.AddedOnly",
$"Advise:{serverHandle}:{addedOnly}",
$"AddItem:{serverHandle}:Tag.Fresh",
$"Advise:{serverHandle}:{fresh}",
$"UnAdvise:{serverHandle}:{addedOnly}",
$"UnAdvise:{serverHandle}:{fresh}",
$"RemoveItem:{serverHandle}:{fresh}",
},
readOperations);
AssertCallerItemIntact(session, serverHandle, cached, "Tag.Cached", expectAdvised: true);
AssertCallerItemIntact(session, serverHandle, advised, "Tag.Advised", expectAdvised: true);
AssertCallerItemIntact(session, serverHandle, addedOnly, "Tag.AddedOnly", expectAdvised: false);
Assert.False(session.HandleRegistry.ContainsItemHandle(serverHandle, fresh));
}
private static void AssertCallerItemIntact(
MxAccessSession session,
int serverHandle,
int itemHandle,
string itemDefinition,
bool expectAdvised)
{
Assert.True(session.HandleRegistry.ContainsItemHandle(serverHandle, itemHandle));
Assert.Contains(itemHandle, session.HandleRegistry.GetItemHandlesForDefinition(serverHandle, itemDefinition));
Assert.Equal(expectAdvised, session.HandleRegistry.ContainsAdviceHandle(serverHandle, itemHandle, MxAccessAdviceKind.Plain));
}
private static void RecordCompletion(MxAccessWriteCompletionCache cache, int serverHandle, int itemHandle) private static void RecordCompletion(MxAccessWriteCompletionCache cache, int serverHandle, int itemHandle)
{ {
RepeatedField<MxStatusProxy> statuses = new() { new MxStatusProxy { Category = MxStatusCategory.Ok } }; RepeatedField<MxStatusProxy> statuses = new() { new MxStatusProxy { Category = MxStatusCategory.Ok } };
@@ -350,6 +350,12 @@ public sealed class MxAccessSession : IDisposable
mxAccessServer.UnAdvise(serverHandle, itemHandle); mxAccessServer.UnAdvise(serverHandle, itemHandle);
handleRegistry.RemoveAdviceHandles(serverHandle, itemHandle); handleRegistry.RemoveAdviceHandles(serverHandle, itemHandle);
// The item stays added but its last value stops updating. Drop it so
// a later re-advise is not answered by ReadBulk's cached fast path
// with the value from the previous advice (including a ReadBulk's
// own temporary advice on a caller's added-only item) before the new
// advice's first OnDataChange lands.
valueCache.Remove(serverHandle, itemHandle);
} }
/// <summary>Advises on item changes with supervisory subscription.</summary> /// <summary>Advises on item changes with supervisory subscription.</summary>
@@ -927,26 +933,49 @@ public sealed class MxAccessSession : IDisposable
/// <summary> /// <summary>
/// Bulk read snapshot. For each requested tag, returns the most recent /// Bulk read snapshot. For each requested tag, returns the most recent
/// OnDataChange value if the tag is already advised AND a cached value /// OnDataChange value if the tag is already advised AND a cached value
/// exists (no subscription side effects); otherwise takes the AddItem /// exists (no subscription side effects); waits on the caller's own
/// + Advise + wait + UnAdvise + RemoveItem snapshot lifecycle itself. /// subscription when the tag is advised but its first OnDataChange has
/// <paramref name="timeout"/> bounds the wait for every snapshot tag; /// not been cached yet; otherwise takes a snapshot lifecycle itself.
/// <paramref name="timeout"/> bounds the wait for every waiting tag;
/// <paramref name="pumpStep"/> is invoked on every poll iteration so the /// <paramref name="pumpStep"/> is invoked on every poll iteration so the
/// worker's STA can dispatch the incoming MXAccess message that carries /// worker's STA can dispatch the incoming MXAccess message that carries
/// the value. /// the value.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// The snapshot tags are processed in phases rather than one at a time: /// <para>
/// every cache probe runs first, then every uncached tag is added and /// The waiting tags are processed in phases rather than one at a
/// advised, then one wait with a single shared deadline collects the /// time: every registry and cache probe runs first, then every tag
/// first OnDataChange per handle, then every snapshot handle is torn /// that needs a subscription is added and/or advised, then one wait
/// down. A serial lifecycle held the STA for up to N x timeout when N /// with a single shared deadline collects the first OnDataChange per
/// tags never produced a value; the phased form holds it for at most /// handle, then the snapshot state this call created is torn down.
/// one timeout. Each tag's result is still its own: a tag that never /// A serial lifecycle held the STA for up to N x timeout when N tags
/// delivered fails with the same timed-out diagnostic and its own item /// never produced a value; the phased form holds it for at most one
/// handle, an AddItem or Advise failure fails only that tag, and results /// timeout. Each tag's result is still its own: a tag that never
/// keep request order. The cache probes run before any snapshot AddItem /// delivered fails with the same timed-out diagnostic and its own
/// so a later tag can never be served from an earlier tag's own /// item handle, an AddItem or Advise failure fails only that tag,
/// snapshot subscription. /// and results keep request order. The cache probes run before any
/// snapshot AddItem so a later tag can never be served from an
/// earlier tag's own snapshot subscription.
/// </para>
/// <para>
/// ReadBulk never removes or unadvises state it did not create
/// (issue #238). Teardown is ownership-scoped: it unadvises only the
/// advices this call's own Advise created and removes only the items
/// this call's own AddItem created. A tag the caller has advised but
/// whose first OnDataChange is not cached yet is read through the
/// caller's own subscription with no COM call at all. Any other tag
/// gets a snapshot AddItem. The installed MXAccess hands that
/// AddItem a new handle even when the caller already holds the
/// address (observed live on windev, 2026-12-01), so a caller's
/// added-but-not-advised item is left untouched and the snapshot
/// item is torn down as before. When AddItem instead returns a
/// handle the registry already tracks, that handle is the caller's:
/// it is advised for the read only if nothing advises it yet,
/// unadvised afterwards (back to its prior added-not-advised state),
/// and never removed — an extra AddItem reference may then outlive
/// the read until the caller removes the item or unregisters, but
/// the caller's item can never be deleted from under it.
/// </para>
/// </remarks> /// </remarks>
/// <param name="serverHandle">The MXAccess server handle.</param> /// <param name="serverHandle">The MXAccess server handle.</param>
/// <param name="tagAddresses">The tag addresses to read.</param> /// <param name="tagAddresses">The tag addresses to read.</param>
@@ -974,10 +1003,13 @@ public sealed class MxAccessSession : IDisposable
BulkReadResult?[] results = new BulkReadResult?[tagCount]; BulkReadResult?[] results = new BulkReadResult?[tagCount];
List<SnapshotRead> snapshots = new(); List<SnapshotRead> snapshots = new();
// Phase 1: validation and the cached-and-advised fast path. A tag // Phase 1: validation, the cached-and-advised fast path, and the
// already advised by the caller with a cached value is answered without // registry probe. A tag already advised by the caller with a cached
// touching the existing subscription — the caller didn't create it, so // value is answered without touching the existing subscription — the
// ReadBulk must not tear it down. // caller created it, so ReadBulk must not tear it down. A tag the
// caller has advised without a cached value yet keeps the caller's
// item handle, so phase 2 waits on that subscription instead of
// re-adding the address and phase 4 never touches it.
for (int index = 0; index < tagCount; index++) for (int index = 0; index < tagCount; index++)
{ {
string? tagAddress = tagAddresses[index]; string? tagAddress = tagAddresses[index];
@@ -987,13 +1019,25 @@ public sealed class MxAccessSession : IDisposable
continue; continue;
} }
if (TryGetCachedReadFor(serverHandle, tagAddress!, out int cachedItemHandle, out MxAccessValueCache.CachedValue cachedValue)) ExistingItemState existing = FindExistingItem(
serverHandle,
tagAddress!,
out int existingItemHandle,
out MxAccessValueCache.CachedValue cachedValue);
if (existing == ExistingItemState.AdvisedAndCached)
{ {
results[index] = SucceededRead(serverHandle, tagAddress!, cachedItemHandle, wasCached: true, cachedValue); results[index] = SucceededRead(serverHandle, tagAddress!, existingItemHandle, wasCached: true, cachedValue);
continue; continue;
} }
snapshots.Add(new SnapshotRead(index, tagAddress!)); SnapshotRead snapshot = new(index, tagAddress!);
if (existing == ExistingItemState.Advised)
{
snapshot.ItemHandle = existingItemHandle;
snapshot.IsCallerItem = true;
}
snapshots.Add(snapshot);
} }
if (snapshots.Count > 0) if (snapshots.Count > 0)
@@ -1035,14 +1079,18 @@ public sealed class MxAccessSession : IDisposable
TimeSpan timeout, TimeSpan timeout,
Action pumpStep) Action pumpStep)
{ {
// Phase 2: reserve our own item handle and advise for every uncached // Phase 2: get an advised item handle for every tag that needs one. A
// tag. A per-tag AddItem/Advise failure fails only that tag. When // tag the caller does not hold gets this call's own AddItem; a tag the
// MXAccess hands back a handle an earlier tag in this batch already // caller holds keeps the caller's handle. The handle is advised only
// advised (a duplicate address), that tag shares the earlier tag's // when nothing advises it yet — an advised caller item is waited on
// subscription instead of advising the handle a second time, and gets // through the caller's own subscription. A per-tag AddItem/Advise
// the same outcome fanned out to it after the wait. // failure fails only that tag. When a handle is already waited on by
// an earlier tag in this batch (a duplicate address), the later tag
// shares that subscription instead of advising the handle a second
// time, and gets the same outcome fanned out to it after the wait.
List<SnapshotRead> waiting = new(snapshots.Count); List<SnapshotRead> waiting = new(snapshots.Count);
Dictionary<int, SnapshotRead> advisedByHandle = new(); Dictionary<int, SnapshotRead> waitingByHandle = new();
HashSet<int> addedHandles = new();
List<SnapshotRead> sharing = new(); List<SnapshotRead> sharing = new();
for (int position = 0; position < snapshots.Count; position++) for (int position = 0; position < snapshots.Count; position++)
{ {
@@ -1054,18 +1102,52 @@ public sealed class MxAccessSession : IDisposable
pumpStep(); pumpStep();
} }
snapshot.ItemHandle = AddItem(serverHandle, snapshot.TagAddress); if (!snapshot.IsCallerItem)
if (advisedByHandle.TryGetValue(snapshot.ItemHandle, out SnapshotRead? owner)) {
snapshot.ItemHandle = AddSnapshotItem(serverHandle, snapshot.TagAddress, out bool alreadyRegistered);
if (!alreadyRegistered)
{
snapshot.OwnsItem = true;
addedHandles.Add(snapshot.ItemHandle);
}
else if (!addedHandles.Contains(snapshot.ItemHandle))
{
// MXAccess returned an item the caller already holds
// (the same address added but not advised, or a
// differently spelled one the ordinal registry lookup
// missed). It is the caller's item: never remove it.
snapshot.IsCallerItem = true;
}
}
if (waitingByHandle.TryGetValue(snapshot.ItemHandle, out SnapshotRead? owner))
{ {
snapshot.SharedWith = owner; snapshot.SharedWith = owner;
sharing.Add(snapshot); sharing.Add(snapshot);
continue; continue;
} }
snapshot.Baseline = valueCache.CurrentVersion(serverHandle, snapshot.ItemHandle); if (IsAdvised(serverHandle, snapshot.ItemHandle))
Advise(serverHandle, snapshot.ItemHandle); {
snapshot.Advised = true; // The caller's subscription already delivers OnDataChange
advisedByHandle[snapshot.ItemHandle] = snapshot; // for this handle. Serve a value that landed since phase 1,
// otherwise wait on that subscription without touching it.
if (valueCache.TryGet(serverHandle, snapshot.ItemHandle, out MxAccessValueCache.CachedValue cachedValue))
{
results[snapshot.Index] = SucceededRead(serverHandle, snapshot.TagAddress, snapshot.ItemHandle, wasCached: true, cachedValue);
continue;
}
snapshot.Baseline = valueCache.CurrentVersion(serverHandle, snapshot.ItemHandle);
}
else
{
snapshot.Baseline = valueCache.CurrentVersion(serverHandle, snapshot.ItemHandle);
Advise(serverHandle, snapshot.ItemHandle);
snapshot.OwnsAdvice = true;
}
waitingByHandle[snapshot.ItemHandle] = snapshot;
waiting.Add(snapshot); waiting.Add(snapshot);
} }
catch (Exception exception) catch (Exception exception)
@@ -1156,15 +1238,18 @@ public sealed class MxAccessSession : IDisposable
List<SnapshotRead> snapshots, List<SnapshotRead> snapshots,
Action pumpStep) Action pumpStep)
{ {
// Phase 4: snapshot teardown — best-effort, never re-throws. Each // Phase 4: snapshot teardown — best-effort, never re-throws, and
// distinct handle is unadvised and removed exactly once, even when // ownership-scoped: only an advice this call's own Advise created is
// unadvised, and only an item this call's own AddItem created is
// removed. A caller's item or subscription is never torn down (#238).
// Each owned handle is unadvised and removed exactly once, even when
// MXAccess handed the same id to several tags in the batch. // MXAccess handed the same id to several tags in the batch.
HashSet<int> unadvised = new(); HashSet<int> unadvised = new();
HashSet<int> removed = new(); HashSet<int> removed = new();
int calls = 0; int calls = 0;
foreach (SnapshotRead snapshot in snapshots) foreach (SnapshotRead snapshot in snapshots)
{ {
if (snapshot.Advised && unadvised.Add(snapshot.ItemHandle)) if (snapshot.OwnsAdvice && unadvised.Add(snapshot.ItemHandle))
{ {
PumpEvery(ref calls, pumpStep); PumpEvery(ref calls, pumpStep);
try { UnAdvise(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ } try { UnAdvise(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ }
@@ -1173,7 +1258,7 @@ public sealed class MxAccessSession : IDisposable
foreach (SnapshotRead snapshot in snapshots) foreach (SnapshotRead snapshot in snapshots)
{ {
if (snapshot.ItemHandle != 0 && removed.Add(snapshot.ItemHandle)) if (snapshot.OwnsItem && removed.Add(snapshot.ItemHandle))
{ {
PumpEvery(ref calls, pumpStep); PumpEvery(ref calls, pumpStep);
try { RemoveItem(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ } try { RemoveItem(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ }
@@ -1191,7 +1276,21 @@ public sealed class MxAccessSession : IDisposable
calls++; calls++;
} }
private bool TryGetCachedReadFor( /// <summary>
/// Classifies the caller's advised items for a tag: none, an advised
/// item with no cached value yet, or an advised item with a cached
/// value. Added-but-not-advised items are skipped: they receive no
/// OnDataChange to wait on, so the tag takes a snapshot AddItem.
/// </summary>
/// <param name="serverHandle">The MXAccess server handle.</param>
/// <param name="tagAddress">The tag address, matched ordinally.</param>
/// <param name="itemHandle">
/// The caller's item handle to read through, or 0 for
/// <see cref="ExistingItemState.None"/>.
/// </param>
/// <param name="cachedValue">The cached value for <see cref="ExistingItemState.AdvisedAndCached"/>.</param>
/// <returns>The strongest state among the tag's advised items.</returns>
private ExistingItemState FindExistingItem(
int serverHandle, int serverHandle,
string tagAddress, string tagAddress,
out int itemHandle, out int itemHandle,
@@ -1202,32 +1301,77 @@ public sealed class MxAccessSession : IDisposable
// no longer walks the whole item table once per tag. The index matches // no longer walks the whole item table once per tag. The index matches
// the tag ordinally and hands the handles back in ascending order — the // the tag ordinally and hands the handles back in ascending order — the
// same order the previous linear scan over the sorted ItemHandles view // same order the previous linear scan over the sorted ItemHandles view
// visited them — so the first advised-and-cached candidate still wins. // visited them — so the first advised-and-cached candidate still wins,
// then the first advised one.
IReadOnlyList<int> candidates = handleRegistry.GetItemHandlesForDefinition(serverHandle, tagAddress); IReadOnlyList<int> candidates = handleRegistry.GetItemHandlesForDefinition(serverHandle, tagAddress);
int firstAdvised = 0;
for (int index = 0; index < candidates.Count; index++) for (int index = 0; index < candidates.Count; index++)
{ {
int candidate = candidates[index]; int candidate = candidates[index];
if (!IsAdvised(serverHandle, candidate))
if (!handleRegistry.ContainsAdviceHandle(serverHandle, candidate, MxAccessAdviceKind.Plain)
&& !handleRegistry.ContainsAdviceHandle(serverHandle, candidate, MxAccessAdviceKind.Supervisory))
{ {
// Tag is added but not advised — no fresh OnDataChange will
// arrive without us advising. Fall through to the snapshot
// path which advises explicitly.
continue; continue;
} }
if (valueCache.TryGet(serverHandle, candidate, out cachedValue)) if (valueCache.TryGet(serverHandle, candidate, out cachedValue))
{ {
itemHandle = candidate; itemHandle = candidate;
return true; return ExistingItemState.AdvisedAndCached;
}
if (firstAdvised == 0)
{
firstAdvised = candidate;
} }
} }
itemHandle = 0;
cachedValue = default; cachedValue = default;
return false; itemHandle = firstAdvised;
return firstAdvised != 0 ? ExistingItemState.Advised : ExistingItemState.None;
}
private bool IsAdvised(
int serverHandle,
int itemHandle)
{
return handleRegistry.ContainsAdviceHandle(serverHandle, itemHandle, MxAccessAdviceKind.Plain)
|| handleRegistry.ContainsAdviceHandle(serverHandle, itemHandle, MxAccessAdviceKind.Supervisory);
}
/// <summary>
/// ReadBulk's own AddItem. Unlike <see cref="AddItem"/> it reports
/// whether MXAccess handed back a handle the registry already tracks,
/// and in that case leaves the existing registration (and its item
/// definition and context) untouched, so the caller can tell its own
/// snapshot item from an item someone else holds.
/// </summary>
/// <param name="serverHandle">The MXAccess server handle.</param>
/// <param name="tagAddress">The tag address to add.</param>
/// <param name="alreadyRegistered">
/// <see langword="true"/> when the returned handle was already in the
/// registry before this AddItem.
/// </param>
/// <returns>The item handle MXAccess returned.</returns>
private int AddSnapshotItem(
int serverHandle,
string tagAddress,
out bool alreadyRegistered)
{
int itemHandle = mxAccessServer.AddItem(serverHandle, tagAddress);
alreadyRegistered = handleRegistry.ContainsItemHandle(serverHandle, itemHandle);
if (!alreadyRegistered)
{
EvictStaleHandleState(serverHandle, itemHandle);
handleRegistry.RegisterItemHandle(
serverHandle,
itemHandle,
tagAddress,
string.Empty,
hasItemContext: false);
}
return itemHandle;
} }
private BulkWriteResult ExecuteBulkWriteEntry( private BulkWriteResult ExecuteBulkWriteEntry(
@@ -1597,14 +1741,33 @@ public sealed class MxAccessSession : IDisposable
/// <summary>Gets the requested tag address.</summary> /// <summary>Gets the requested tag address.</summary>
public string TagAddress { get; } public string TagAddress { get; }
/// <summary>Gets or sets the snapshot item handle, 0 until AddItem succeeds.</summary> /// <summary>
/// Gets or sets the item handle the read goes through: the caller's
/// own handle, or the snapshot handle (0 until AddItem succeeds).
/// </summary>
public int ItemHandle { get; set; } public int ItemHandle { get; set; }
/// <summary>Gets or sets the value-cache version captured before Advise.</summary> /// <summary>Gets or sets the value-cache version captured before the wait.</summary>
public ulong Baseline { get; set; } public ulong Baseline { get; set; }
/// <summary>Gets or sets a value indicating whether Advise succeeded.</summary> /// <summary>
public bool Advised { get; set; } /// Gets or sets a value indicating whether <see cref="ItemHandle"/>
/// is an item the session held before this ReadBulk, which teardown
/// must never remove.
/// </summary>
public bool IsCallerItem { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this ReadBulk's own
/// AddItem created the item, so teardown removes it.
/// </summary>
public bool OwnsItem { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this ReadBulk's own
/// Advise created the advice, so teardown unadvises it.
/// </summary>
public bool OwnsAdvice { get; set; }
/// <summary> /// <summary>
/// Gets or sets the earlier snapshot in the same batch whose /// Gets or sets the earlier snapshot in the same batch whose
@@ -1613,6 +1776,19 @@ public sealed class MxAccessSession : IDisposable
public SnapshotRead? SharedWith { get; set; } public SnapshotRead? SharedWith { get; set; }
} }
/// <summary>What the caller has advised for a ReadBulk tag before the read.</summary>
private enum ExistingItemState
{
/// <summary>No advised item for the tag: the read takes a snapshot AddItem.</summary>
None,
/// <summary>An advised item with no cached value: the read waits on that subscription.</summary>
Advised,
/// <summary>An advised item with a cached value: the read is served from the cache.</summary>
AdvisedAndCached,
}
private void ThrowIfDisposed() private void ThrowIfDisposed()
{ {
if (disposed) if (disposed)