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.
This commit is contained in:
Joseph Doherty
2026-12-01 19:25:19 -05:00
parent 54367e7408
commit 7a41d9edea
8 changed files with 520 additions and 78 deletions
+7 -4
View File
@@ -88,10 +88,13 @@ of items per round trip while preserving MXAccess parity per entry.
`was_successful`, `was_cached`, `value`, `quality`, `source_timestamp`,
`repeated MxStatusProxy statuses`, and `error_message`. MXAccess has no
synchronous `Read`, so `ReadBulk` is dual-mode per entry: when a tag is
already advised in the session the worker returns the cached
`OnDataChange` payload without touching the subscription
(`was_cached = true`); otherwise the worker takes a full
`AddItem` + `Advise` + wait-for-first-`OnDataChange` + `UnAdvise` +
already advised in the session and has a cached value the worker returns
the cached `OnDataChange` payload without touching the subscription
(`was_cached = true`); a tag the session holds without a cached value is
read through the caller's own item handle — waiting on its existing
subscription, or advising an added-only item for the read and
unadvising it after — and is never removed; otherwise the worker takes a
full `AddItem` + `Advise` + wait-for-first-`OnDataChange` + `UnAdvise` +
`RemoveItem` snapshot lifecycle and returns the result
(`was_cached = false`). The asymmetry that `BulkReadResult` has no
`hresult` field is intentional — `ReadBulk` outcomes are timeout / cache
+23 -6
View File
@@ -532,7 +532,21 @@ choices were considered:
(`was_cached = true`). Otherwise it takes the full `AddItem + Advise +
wait-for-first-OnDataChange + UnAdvise + RemoveItem` lifecycle itself
(`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. A tag the session already holds is read through the
caller's item handle with no `AddItem` — an advised tag whose first
`OnDataChange` is not cached yet is waited on through the caller's
subscription, and an added-but-not-advised tag is advised for the read
and unadvised afterwards, which returns it to the caller's prior state;
neither is ever removed. Re-adding the caller's address instead returns
the caller's own handle from MXAccess, and the old symmetric teardown
then unadvised and removed the caller's item — a subscription that
delivered one value and went silent (#238). A snapshot `AddItem` that
still returns a handle the registry already tracks (an address spelled
differently from the caller's) is never removed either; at worst that
leaves one extra `AddItem` reference 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
event clears the outbound queue.
@@ -543,12 +557,15 @@ choices were considered:
The chosen behavior matches what callers actually want from "current
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
from the snapshot path: the snapshot value reaches the caller through
`ReadBulk`'s reply payload only, not through the event stream. This
preserves the "Don't synthesize events" rule that scopes the rest of the
worker.
from the snapshot path: the worker adds no event of its own for the
snapshot value, which reaches the caller through `ReadBulk`'s reply
payload. The native `OnDataChange` MXAccess raises for a handle the read
advised still flows through the event sink like any other — including,
for an added-but-not-advised caller item, under the caller's own item
handle while the read holds it advised. 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
(`StaRuntime.PumpPendingMessages`) on every poll iteration so the inbound
+13 -4
View File
@@ -355,10 +355,19 @@ timeout.
`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
probed against the cached-and-advised fast path; (2) every remaining tag is
added and advised; (3) one wait with a shared deadline collects the first
`OnDataChange` per snapshot handle and returns as soon as all have delivered;
(4) every snapshot handle is unadvised and removed, best-effort. Per-tag
probed against the registry and the cached-and-advised fast path; (2) every
remaining tag gets an advised handle — a tag the session does not hold gets
the read's own `AddItem`, a tag it holds keeps the caller's item handle, and
the 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: an advised-but-uncached caller tag is waited on
through the existing subscription with no COM call, and an added-only caller
item is advised for the read and unadvised afterwards, back to its prior
state (#238). A snapshot `AddItem` that returns a handle the registry already
tracks is treated as the caller's item for the same reason. Per-tag
results are unchanged: request order, the blank-address failure, the cached
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
+12 -4
View File
@@ -570,11 +570,19 @@ returns one result per requested entry — per-entry failures populate
last cached `OnDataChange` payload when the requested tag is already
advised (`was_cached = true`, no subscription side-effects), or by
taking a full `AddItem` + `Advise` + wait-for-first-OnDataChange +
`UnAdvise` + `RemoveItem` snapshot lifecycle when no live subscription
exists (`was_cached = false`). `timeout_ms` is one shared deadline for
`UnAdvise` + `RemoveItem` snapshot lifecycle when the session holds no
item for the tag (`was_cached = false`). A tag the session already holds
is read through the caller's own item handle and is never re-added or
removed: advised but not yet cached, the worker waits on the caller's
subscription with no COM call; added but not advised, it advises the
item for the read and unadvises it afterwards, returning it to the
caller's prior added-not-advised state (both `was_cached = false`).
Teardown only undoes the `AddItem` and `Advise` calls the read itself
made, 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
every uncached tag first, waits once for all of them, then tears them
all down, so the STA is held for at most one `timeout_ms` (plus the
every tag that needs it first, waits once for all of them, then tears
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).
Each tag that has not delivered by the deadline surfaces its own
`was_successful = false` timeout rather than throwing. Duplicate
@@ -715,8 +715,8 @@ public sealed class MxAccessCommandExecutorTests
new ZB.MOM.WW.MxGateway.Worker.Conversion.VariantConverter());
// Registry half of the fast path: the tag must resolve to a live item
// handle on this server AND carry an advice, or TryGetCachedReadFor
// falls through to the AddItem/Advise snapshot lifecycle.
// handle on this server AND carry an advice and a cached value, or
// FindExistingItem sends the tag to the wait/snapshot path.
MxCommandReply registerReply = executor.Execute(
CreateRegisterCommand("register-before-cached-read", "client-a"));
MxCommandReply addItemReply = executor.Execute(
@@ -257,11 +257,11 @@ public sealed class MxAccessHandleRegistryTests
}
/// <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"/>
/// in order and skips any candidate carrying neither a plain nor a supervisory advice,
/// because an added-but-unadvised item will never receive a fresh <c>OnDataChange</c> and so
/// can only serve a stale cache entry. The registry has to make that skip possible: the
/// in order and never serves the cache of a candidate carrying neither a plain nor a
/// supervisory advice, because an added-but-unadvised item will never receive a fresh
/// <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
/// 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.
@@ -428,6 +428,231 @@ public sealed class MxAccessSessionTests
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, as
/// MXAccess does, 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 is advised for the read
/// and unadvised afterwards — returning the caller's item to its prior
/// added-not-advised state — but never re-added and never removed.
/// </summary>
[Fact]
public void ReadBulk_AddedButNotAdvisedTag_AdvisesForTheReadThenUnAdvisesButNeverRemovesTheCallersItem()
{
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[] { $"Advise:{serverHandle}:{callerHandle}", $"UnAdvise:{serverHandle}:{callerHandle}" },
server.Operations.Skip(operationsBeforeRead));
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.AddedOnly", expectAdvised: false);
}
/// <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.
/// </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[]
{
$"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)
{
RepeatedField<MxStatusProxy> statuses = new() { new MxStatusProxy { Category = MxStatusCategory.Ok } };
@@ -927,26 +927,47 @@ public sealed class MxAccessSession : IDisposable
/// <summary>
/// Bulk read snapshot. For each requested tag, returns the most recent
/// OnDataChange value if the tag is already advised AND a cached value
/// exists (no subscription side effects); otherwise takes the AddItem
/// + Advise + wait + UnAdvise + RemoveItem snapshot lifecycle itself.
/// <paramref name="timeout"/> bounds the wait for every snapshot tag;
/// exists (no subscription side effects); waits on the caller's own
/// subscription when the tag is advised but its first OnDataChange has
/// 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
/// worker's STA can dispatch the incoming MXAccess message that carries
/// the value.
/// </summary>
/// <remarks>
/// The snapshot tags are processed in phases rather than one at a time:
/// every cache probe runs first, then every uncached tag is added and
/// advised, then one wait with a single shared deadline collects the
/// first OnDataChange per handle, then every snapshot handle is torn
/// down. A serial lifecycle held the STA for up to N x timeout when N
/// tags never produced a value; the phased form holds it for at most
/// one timeout. Each tag's result is still its own: a tag that never
/// delivered fails with the same timed-out diagnostic and its own item
/// handle, an AddItem or Advise failure fails only that tag, 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>
/// The waiting tags are processed in phases rather than one at a
/// time: every registry and cache probe runs first, then every tag
/// that needs a subscription is added and/or advised, then one wait
/// with a single shared deadline collects the first OnDataChange per
/// handle, then the snapshot state this call created is torn down.
/// A serial lifecycle held the STA for up to N x timeout when N tags
/// never produced a value; the phased form holds it for at most one
/// timeout. Each tag's result is still its own: a tag that never
/// delivered fails with the same timed-out diagnostic and its own
/// item handle, an AddItem or Advise failure fails only that tag,
/// 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 session already holds
/// is read through the caller's item handle without an AddItem:
/// advised, it waits on the existing subscription with no COM call
/// at all; added but not advised, it is advised for the read and
/// unadvised afterwards, which returns the item to the caller's
/// prior added-not-advised state — it is never removed. A snapshot
/// AddItem that hands back a handle the registry already tracks (an
/// address spelled differently from the caller's, which the ordinal
/// registry lookup misses) is treated the same way and is never
/// removed, so an extra AddItem reference can leak until the caller
/// removes the item or unregisters, but the caller's item can never
/// be deleted from under it.
/// </para>
/// </remarks>
/// <param name="serverHandle">The MXAccess server handle.</param>
/// <param name="tagAddresses">The tag addresses to read.</param>
@@ -974,10 +995,12 @@ public sealed class MxAccessSession : IDisposable
BulkReadResult?[] results = new BulkReadResult?[tagCount];
List<SnapshotRead> snapshots = new();
// Phase 1: validation and the cached-and-advised fast path. A tag
// already advised by the caller with a cached value is answered without
// touching the existing subscription — the caller didn't create it, so
// ReadBulk must not tear it down.
// Phase 1: validation, the cached-and-advised fast path, and the
// registry probe. A tag already advised by the caller with a cached
// value is answered without touching the existing subscription — the
// caller created it, so ReadBulk must not tear it down. A tag the
// caller already holds without a cached value keeps the caller's item
// handle so phase 2 never re-adds (and phase 4 never removes) it.
for (int index = 0; index < tagCount; index++)
{
string? tagAddress = tagAddresses[index];
@@ -987,13 +1010,25 @@ public sealed class MxAccessSession : IDisposable
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;
}
snapshots.Add(new SnapshotRead(index, tagAddress!));
SnapshotRead snapshot = new(index, tagAddress!);
if (existing != ExistingItemState.None)
{
snapshot.ItemHandle = existingItemHandle;
snapshot.IsCallerItem = true;
}
snapshots.Add(snapshot);
}
if (snapshots.Count > 0)
@@ -1035,14 +1070,18 @@ public sealed class MxAccessSession : IDisposable
TimeSpan timeout,
Action pumpStep)
{
// Phase 2: reserve our own item handle and advise for every uncached
// tag. A per-tag AddItem/Advise failure fails only that tag. When
// MXAccess hands back a handle an earlier tag in this batch already
// advised (a duplicate address), that tag shares the earlier tag's
// subscription instead of advising the handle a second time, and gets
// the same outcome fanned out to it after the wait.
// Phase 2: get an advised item handle for every tag that needs one. A
// tag the caller does not hold gets this call's own AddItem; a tag the
// caller holds keeps the caller's handle. The handle is advised only
// when nothing advises it yet — an advised caller item is waited on
// through the caller's own subscription. A per-tag AddItem/Advise
// 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);
Dictionary<int, SnapshotRead> advisedByHandle = new();
Dictionary<int, SnapshotRead> waitingByHandle = new();
HashSet<int> addedHandles = new();
List<SnapshotRead> sharing = new();
for (int position = 0; position < snapshots.Count; position++)
{
@@ -1054,18 +1093,51 @@ public sealed class MxAccessSession : IDisposable
pumpStep();
}
snapshot.ItemHandle = AddItem(serverHandle, snapshot.TagAddress);
if (advisedByHandle.TryGetValue(snapshot.ItemHandle, out SnapshotRead? owner))
if (!snapshot.IsCallerItem)
{
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 resolved this address to an item the caller
// already holds under a different spelling. It is the
// caller's item: never remove it.
snapshot.IsCallerItem = true;
}
}
if (waitingByHandle.TryGetValue(snapshot.ItemHandle, out SnapshotRead? owner))
{
snapshot.SharedWith = owner;
sharing.Add(snapshot);
continue;
}
snapshot.Baseline = valueCache.CurrentVersion(serverHandle, snapshot.ItemHandle);
Advise(serverHandle, snapshot.ItemHandle);
snapshot.Advised = true;
advisedByHandle[snapshot.ItemHandle] = snapshot;
if (IsAdvised(serverHandle, snapshot.ItemHandle))
{
// The caller's subscription already delivers OnDataChange
// 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);
}
catch (Exception exception)
@@ -1156,15 +1228,18 @@ public sealed class MxAccessSession : IDisposable
List<SnapshotRead> snapshots,
Action pumpStep)
{
// Phase 4: snapshot teardown — best-effort, never re-throws. Each
// distinct handle is unadvised and removed exactly once, even when
// Phase 4: snapshot teardown — best-effort, never re-throws, and
// 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.
HashSet<int> unadvised = new();
HashSet<int> removed = new();
int calls = 0;
foreach (SnapshotRead snapshot in snapshots)
{
if (snapshot.Advised && unadvised.Add(snapshot.ItemHandle))
if (snapshot.OwnsAdvice && unadvised.Add(snapshot.ItemHandle))
{
PumpEvery(ref calls, pumpStep);
try { UnAdvise(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ }
@@ -1173,7 +1248,7 @@ public sealed class MxAccessSession : IDisposable
foreach (SnapshotRead snapshot in snapshots)
{
if (snapshot.ItemHandle != 0 && removed.Add(snapshot.ItemHandle))
if (snapshot.OwnsItem && removed.Add(snapshot.ItemHandle))
{
PumpEvery(ref calls, pumpStep);
try { RemoveItem(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ }
@@ -1191,7 +1266,20 @@ public sealed class MxAccessSession : IDisposable
calls++;
}
private bool TryGetCachedReadFor(
/// <summary>
/// Classifies what the session already holds for a tag: nothing, an
/// added-but-not-advised item, an advised item with no cached value
/// yet, or an advised item with a cached value.
/// </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 registered items.</returns>
private ExistingItemState FindExistingItem(
int serverHandle,
string tagAddress,
out int itemHandle,
@@ -1202,32 +1290,89 @@ public sealed class MxAccessSession : IDisposable
// 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
// 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, then the first added one.
IReadOnlyList<int> candidates = handleRegistry.GetItemHandlesForDefinition(serverHandle, tagAddress);
int firstAdvised = 0;
int firstAdded = 0;
for (int index = 0; index < candidates.Count; index++)
{
int candidate = candidates[index];
if (!handleRegistry.ContainsAdviceHandle(serverHandle, candidate, MxAccessAdviceKind.Plain)
&& !handleRegistry.ContainsAdviceHandle(serverHandle, candidate, MxAccessAdviceKind.Supervisory))
if (firstAdded == 0)
{
firstAdded = candidate;
}
if (!IsAdvised(serverHandle, candidate))
{
// Tag is added but not advised — no fresh OnDataChange will
// arrive without us advising. Fall through to the snapshot
// path which advises explicitly.
continue;
}
if (valueCache.TryGet(serverHandle, candidate, out cachedValue))
{
itemHandle = candidate;
return true;
return ExistingItemState.AdvisedAndCached;
}
if (firstAdvised == 0)
{
firstAdvised = candidate;
}
}
itemHandle = 0;
cachedValue = default;
return false;
if (firstAdvised != 0)
{
itemHandle = firstAdvised;
return ExistingItemState.Advised;
}
itemHandle = firstAdded;
return firstAdded != 0 ? ExistingItemState.Added : 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(
@@ -1597,14 +1742,33 @@ public sealed class MxAccessSession : IDisposable
/// <summary>Gets the requested tag address.</summary>
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; }
/// <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; }
/// <summary>Gets or sets a value indicating whether Advise succeeded.</summary>
public bool Advised { get; set; }
/// <summary>
/// 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>
/// Gets or sets the earlier snapshot in the same batch whose
@@ -1613,6 +1777,22 @@ public sealed class MxAccessSession : IDisposable
public SnapshotRead? SharedWith { get; set; }
}
/// <summary>What the session already holds for a ReadBulk tag before the read.</summary>
private enum ExistingItemState
{
/// <summary>No registered item for the tag: the read takes its own snapshot item.</summary>
None,
/// <summary>An item is registered but not advised: the read advises it temporarily.</summary>
Added,
/// <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()
{
if (disposed)