fix(worker): ReadBulk never tears down the caller's own item or advice (#238)

ReadBulk served a tag from the cache only when it was advised and cached;
every other tag took the AddItem + Advise + wait + UnAdvise + RemoveItem
snapshot lifecycle. If AddItem ever returned the caller's existing handle,
the teardown would unadvise and remove the caller's subscription.

ReadBulk now resolves a tag the session already holds to the session's
own item handle in phase 1:
- advised but uncached: wait on the caller's subscription for its first
  OnDataChange (baseline taken in phase 1, before any phase-2 pump can
  dispatch it); no COM call, no teardown.
- added but not advised: advise temporarily, then unadvise only; the item
  stays registered, and the value the temporary advice cached is dropped
  so it cannot later be served as was_cached = true.
- not held: unchanged snapshot lifecycle. An AddItem that returns a handle
  the registry already tracks is treated as the caller's (not
  re-registered, not removed).
Duplicate sharing, pump cadence, the shared deadline, timeout reporting
and was_cached semantics are unchanged.

Live repro on the windev rig (330 advised + 40 added-only tags, immediate
250-tag ReadBulk chunks x4 parallel, 60 s observation): unfixed and fixed
workers both keep 290/330 handles delivering. The 40 silent handles are
TestHistoryValue, which does not change within the window on either
build. The installed MXAccess hands out a distinct handle per AddItem
even for an address already added, and UnAdvise/RemoveItem of the second
handle leaves the first delivering. So the #238 teardown path does not
silence subscriptions on this MXAccess, and this change does not explain
the vd03 rate drop. The fix stays as a guard, and it saves an extra item
and four COM calls per uncached held tag.

Docs: gateway.md, Contracts.md, DesignDecisions.md,
MxAccessWorkerInstanceDesign.md and the five client ReadBulk doc comments.
This commit is contained in:
Joseph Doherty
2026-11-21 16:49:37 -05:00
parent 90d2d4a9b1
commit e934854a89
11 changed files with 470 additions and 59 deletions
@@ -428,6 +428,216 @@ public sealed class MxAccessSessionTests
Assert.Contains(pumpAtOperation, at => at > firstUnAdvise);
}
/// <summary>
/// #238 case (a): a tag the caller advised whose first OnDataChange has
/// not been cached yet is read through the caller's own subscription.
/// ReadBulk makes no AddItem/Advise/UnAdvise/RemoveItem call for it,
/// returns the value when it arrives, and the subscription keeps
/// delivering afterwards.
/// </summary>
[Fact]
public void ReadBulk_CallerAdvisedUncachedTag_WaitsOnTheCallerSubscriptionWithoutTouchingIt()
{
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int handle = session.AddItem(serverHandle, "Tag.Sub");
session.AdviseSupervisory(serverHandle, handle);
int operationsBefore = server.Operations.Count;
// The caller's first OnDataChange lands while ReadBulk waits.
int pumps = 0;
Action pumpStep = () =>
{
if (++pumps == 3)
{
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, 41));
}
};
BulkReadResult result = Assert.Single(session.ReadBulk(serverHandle, new[] { "Tag.Sub" }, TimeSpan.FromSeconds(5), pumpStep));
Assert.True(result.WasSuccessful, result.ErrorMessage);
Assert.False(result.WasCached);
Assert.Equal(handle, result.ItemHandle);
Assert.Equal(41, result.Value.Int32Value);
Assert.Empty(server.Operations.Skip(operationsBefore));
Assert.True(server.TryGetAdvisedHandle("Tag.Sub", out _));
Assert.True(session.HandleRegistry.ContainsItemHandle(serverHandle, handle));
Assert.True(session.HandleRegistry.ContainsAdviceHandle(serverHandle, handle, MxAccessAdviceKind.Supervisory));
// A later OnDataChange on the caller's subscription is still served.
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, 42));
BulkReadResult later = Assert.Single(session.ReadBulk(serverHandle, new[] { "Tag.Sub" }, TimeSpan.FromSeconds(5), () => { }));
Assert.True(later.WasCached);
Assert.Equal(42, later.Value.Int32Value);
}
/// <summary>
/// The caller's first OnDataChange for an advised-uncached tag can be
/// dispatched by a phase-2 pump, before the wait starts. Its baseline is
/// taken in phase 1, so that value still satisfies the read instead of
/// the tag waiting for a second change and timing out.
/// </summary>
[Fact]
public void ReadBulk_CallerAdvisedTagDeliveringDuringAddAdvisePhase_StillSucceeds()
{
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.Sub");
session.Advise(serverHandle, handle);
string[] tags = new[] { "Tag.Sub" }
.Concat(Enumerable.Range(0, 2 * MxAccessSession.ReadBulkPumpInterval).Select(i => "Tag.Other" + i))
.ToArray();
bool delivered = false;
Action pumpStep = () =>
{
if (!delivered)
{
delivered = true;
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, 9));
}
};
IReadOnlyList<BulkReadResult> results = session.ReadBulk(serverHandle, tags, TimeSpan.FromMilliseconds(100), pumpStep);
Assert.True(results[0].WasSuccessful, results[0].ErrorMessage);
Assert.Equal(9, results[0].Value.Int32Value);
}
/// <summary>
/// #238 case (b): a tag the caller added but did not advise is advised
/// temporarily to get a value. Teardown unadvises it but never removes
/// the caller's item, the handle stays registered, and the value the
/// temporary advice cached is dropped so it cannot later be served as
/// <c>was_cached = true</c>.
/// </summary>
[Fact]
public void ReadBulk_CallerAddedUnadvisedTag_UnadvisesButKeepsTheCallerItem()
{
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int handle = session.AddItem(serverHandle, "Tag.Added");
int operationsBefore = server.Operations.Count;
Action pumpStep = () =>
{
if (server.TryGetAdvisedHandle("Tag.Added", out int advised) && !valueCache.TryGet(serverHandle, advised, out _))
{
valueCache.Set(serverHandle, advised, BuildDataChange(serverHandle, advised, 5));
}
};
BulkReadResult result = Assert.Single(session.ReadBulk(serverHandle, new[] { "Tag.Added" }, TimeSpan.FromSeconds(5), pumpStep));
Assert.True(result.WasSuccessful, result.ErrorMessage);
Assert.False(result.WasCached);
Assert.Equal(handle, result.ItemHandle);
Assert.Equal(5, result.Value.Int32Value);
Assert.Equal(
new[] { "Advise:" + serverHandle + ":" + handle, "UnAdvise:" + serverHandle + ":" + handle },
server.Operations.Skip(operationsBefore).ToArray());
RegisteredItemHandle registered = Assert.Single(session.HandleRegistry.ItemHandles);
Assert.Equal(handle, registered.ItemHandle);
Assert.Equal("Tag.Added", registered.ItemDefinition);
Assert.Empty(session.HandleRegistry.AdviceHandles);
Assert.False(valueCache.TryGet(serverHandle, handle, out _));
}
/// <summary>
/// A tag the registry does not know under that spelling can still make
/// MXAccess hand back a handle the caller holds. That handle is the
/// caller's: ReadBulk neither removes it nor overwrites its registered
/// definition.
/// </summary>
[Fact]
public void ReadBulk_AddItemReturningACallerHandle_DoesNotRemoveOrReRegisterIt()
{
RecordingMxAccessServer server = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink());
int serverHandle = session.Register("client");
int handle = session.AddItem(serverHandle, "Tag.Case");
server.NextItemHandleOverride = handle;
BulkReadResult result = Assert.Single(session.ReadBulk(serverHandle, new[] { "TAG.CASE" }, TimeSpan.FromMilliseconds(30), () => { }));
Assert.Equal(handle, result.ItemHandle);
Assert.DoesNotContain("RemoveItem:" + serverHandle + ":" + handle, server.Operations);
Assert.Contains("UnAdvise:" + serverHandle + ":" + handle, server.Operations);
RegisteredItemHandle registered = Assert.Single(session.HandleRegistry.ItemHandles);
Assert.Equal("Tag.Case", registered.ItemDefinition);
}
/// <summary>
/// #238 case (d): one batch mixing a caller-advised tag, a caller-added
/// tag and a tag ReadBulk adds itself, each requested twice. Each handle
/// is touched at most once, only ReadBulk's own item is removed, and
/// every duplicate receives its owner's outcome.
/// </summary>
[Fact]
public void ReadBulk_MixedOwnershipBatchWithDuplicates_TearsDownOnlyWhatItCreated()
{
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
MxAccessValueCache valueCache = new();
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
int serverHandle = session.Register("client");
int subscribed = session.AddItem(serverHandle, "Tag.Sub");
session.AdviseSupervisory(serverHandle, subscribed);
int added = session.AddItem(serverHandle, "Tag.Added");
int operationsBefore = server.Operations.Count;
Action pumpStep = () =>
{
foreach (string tag in new[] { "Tag.Sub", "Tag.Added", "Tag.New" })
{
if (server.TryGetAdvisedHandle(tag, out int advised) && !valueCache.TryGet(serverHandle, advised, out _))
{
valueCache.Set(serverHandle, advised, BuildDataChange(serverHandle, advised, advised));
}
}
};
string[] tags = { "Tag.Sub", "Tag.Added", "Tag.New", "Tag.Sub", "Tag.Added", "Tag.New" };
IReadOnlyList<BulkReadResult> results = session.ReadBulk(serverHandle, tags, TimeSpan.FromSeconds(5), pumpStep);
int created = server.HandleForTag("Tag.New");
Assert.All(results, r => Assert.True(r.WasSuccessful, r.ErrorMessage));
for (int index = 0; index < tags.Length; index++)
{
Assert.Equal(tags[index], results[index].TagAddress);
Assert.Equal(results[index].ItemHandle, results[index].Value.Int32Value);
}
Assert.Equal(subscribed, results[3].ItemHandle);
Assert.Equal(added, results[4].ItemHandle);
Assert.Equal(created, results[5].ItemHandle);
// Each request for the unregistered Tag.New makes its own AddItem;
// the second resolves to the first's handle and shares its wait.
string[] expected =
{
"AddItem:" + serverHandle + ":Tag.New",
"AddItem:" + serverHandle + ":Tag.New",
"Advise:" + serverHandle + ":" + added,
"Advise:" + serverHandle + ":" + created,
"UnAdvise:" + serverHandle + ":" + added,
"UnAdvise:" + serverHandle + ":" + created,
"RemoveItem:" + serverHandle + ":" + created,
};
Assert.Equal(expected.OrderBy(op => op, StringComparer.Ordinal), server.Operations.Skip(operationsBefore).OrderBy(op => op, StringComparer.Ordinal));
Assert.Equal(new[] { subscribed, added }, session.HandleRegistry.ItemHandles.Select(h => h.ItemHandle).ToArray());
RegisteredAdviceHandle advice = Assert.Single(session.HandleRegistry.AdviceHandles);
Assert.Equal(subscribed, advice.ItemHandle);
Assert.Equal(MxAccessAdviceKind.Supervisory, advice.AdviceKind);
Assert.True(server.TryGetAdvisedHandle("Tag.Sub", out _));
}
private static void RecordCompletion(MxAccessWriteCompletionCache cache, int serverHandle, int itemHandle)
{
RepeatedField<MxStatusProxy> statuses = new() { new MxStatusProxy { Category = MxStatusCategory.Ok } };
@@ -927,8 +927,13 @@ 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.
/// exists (no subscription side effects); otherwise waits for the first
/// OnDataChange. A tag the caller already advised is waited on through
/// the caller's own subscription, untouched; a tag the caller added but
/// did not advise is advised temporarily and unadvised afterwards, its
/// item kept; any other tag takes the AddItem + Advise + wait +
/// UnAdvise + RemoveItem snapshot lifecycle itself. ReadBulk never
/// unadvises or removes anything the caller created.
/// <paramref name="timeout"/> bounds the wait for every snapshot tag;
/// <paramref name="pumpStep"/> is invoked on every poll iteration so the
/// worker's STA can dispatch the incoming MXAccess message that carries
@@ -993,7 +998,31 @@ public sealed class MxAccessSession : IDisposable
continue;
}
snapshots.Add(new SnapshotRead(index, tagAddress!));
// A tag the caller already added (advised or not) is read through
// the caller's own item handle rather than a fresh AddItem (#238).
// The installed MXAccess hands out a new handle per AddItem even
// for an address already added, so a separate snapshot item does
// not disturb the caller's; but it costs an extra item plus four
// COM calls per tag, and the snapshot teardown would destroy the
// caller's item and advice on any build or address form that hands
// back the existing handle. Phase 2 only advises the caller's
// handle when the caller has not, and phase 4 never removes it.
SnapshotRead snapshot = new(index, tagAddress!);
if (TryGetRegisteredHandleFor(serverHandle, tagAddress!, out int registeredItemHandle, out bool callerAdvised))
{
snapshot.ItemHandle = registeredItemHandle;
if (callerAdvised)
{
// Capture the baseline now, before any phase-2 pump can
// dispatch the caller's first OnDataChange; a later capture
// would count that value as already seen and wait for a
// second one.
snapshot.Baseline = valueCache.CurrentVersion(serverHandle, registeredItemHandle);
snapshot.BaselineCaptured = true;
}
}
snapshots.Add(snapshot);
}
if (snapshots.Count > 0)
@@ -1035,14 +1064,22 @@ 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: make sure every uncached tag has an advised item handle to
// wait on. A per-tag AddItem/Advise failure fails only that tag.
// - A tag the caller never added gets ReadBulk's own AddItem and
// Advise; ReadBulk owns both and phase 4 undoes both.
// - A tag the caller added but did not advise (phase 1 resolved its
// handle, or AddItem handed back a handle the registry already
// tracked) is advised temporarily; phase 4 undoes only the advice.
// - A tag the caller already advised is waited on through the
// caller's own subscription; ReadBulk makes no COM call for it and
// phase 4 leaves it alone.
// When a handle is already in play earlier in this batch (a duplicate
// address), the later tag shares the earlier tag's wait instead of
// touching 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();
List<SnapshotRead> sharing = new();
for (int position = 0; position < snapshots.Count; position++)
{
@@ -1054,18 +1091,32 @@ public sealed class MxAccessSession : IDisposable
pumpStep();
}
snapshot.ItemHandle = AddItem(serverHandle, snapshot.TagAddress);
if (advisedByHandle.TryGetValue(snapshot.ItemHandle, out SnapshotRead? owner))
if (snapshot.ItemHandle == 0)
{
snapshot.ItemHandle = AddSnapshotItem(serverHandle, snapshot.TagAddress, out bool ownsItem);
snapshot.OwnsItem = ownsItem;
}
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 (!snapshot.BaselineCaptured)
{
snapshot.Baseline = valueCache.CurrentVersion(serverHandle, snapshot.ItemHandle);
snapshot.BaselineCaptured = true;
}
if (!IsAdvised(serverHandle, snapshot.ItemHandle))
{
Advise(serverHandle, snapshot.ItemHandle);
snapshot.Advised = true;
}
waitingByHandle[snapshot.ItemHandle] = snapshot;
waiting.Add(snapshot);
}
catch (Exception exception)
@@ -1156,9 +1207,12 @@ 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
// MXAccess handed the same id to several tags in the batch.
// Phase 4: snapshot teardown — best-effort, never re-throws. It undoes
// only what phase 2 did: an advice ReadBulk made is unadvised and an
// item ReadBulk added is removed, each exactly once even when MXAccess
// handed the same id to several tags in the batch. A handle the
// caller held before this call keeps its item, and keeps its advice
// unless ReadBulk was the one that advised it.
HashSet<int> unadvised = new();
HashSet<int> removed = new();
int calls = 0;
@@ -1167,13 +1221,29 @@ public sealed class MxAccessSession : IDisposable
if (snapshot.Advised && unadvised.Add(snapshot.ItemHandle))
{
PumpEvery(ref calls, pumpStep);
try { UnAdvise(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ }
try
{
UnAdvise(serverHandle, snapshot.ItemHandle);
if (!snapshot.OwnsItem)
{
// The caller's item outlives this call, so drop the
// value ReadBulk's temporary advice cached: a later
// caller Advise followed by a ReadBulk must wait for
// the caller's own OnDataChange instead of being served
// this snapshot as was_cached = true.
valueCache.Remove(serverHandle, snapshot.ItemHandle);
}
}
catch
{
// swallow — best effort
}
}
}
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 */ }
@@ -1181,6 +1251,78 @@ public sealed class MxAccessSession : IDisposable
}
}
/// <summary>
/// AddItem for a tag phase 1 found no registered handle for. Should
/// MXAccess hand back a handle the registry already tracks (for example
/// an address it treats as the same item under a different spelling),
/// that handle is the caller's, so it is neither re-registered (which
/// would overwrite the caller's definition and context) nor owned by
/// ReadBulk.
/// </summary>
private int AddSnapshotItem(
int serverHandle,
string tagAddress,
out bool ownsItem)
{
int itemHandle = mxAccessServer.AddItem(serverHandle, tagAddress);
if (handleRegistry.ContainsItemHandle(serverHandle, itemHandle))
{
ownsItem = false;
return itemHandle;
}
EvictStaleHandleState(serverHandle, itemHandle);
handleRegistry.RegisterItemHandle(
serverHandle,
itemHandle,
tagAddress,
string.Empty,
hasItemContext: false);
ownsItem = true;
return itemHandle;
}
private bool IsAdvised(
int serverHandle,
int itemHandle)
{
return handleRegistry.ContainsAdviceHandle(serverHandle, itemHandle, MxAccessAdviceKind.Plain)
|| handleRegistry.ContainsAdviceHandle(serverHandle, itemHandle, MxAccessAdviceKind.Supervisory);
}
/// <summary>
/// Finds an item handle the caller already registered for the tag,
/// preferring one the caller has advised (its subscription will deliver
/// the value without ReadBulk touching it).
/// </summary>
private bool TryGetRegisteredHandleFor(
int serverHandle,
string tagAddress,
out int itemHandle,
out bool advised)
{
IReadOnlyList<int> candidates = handleRegistry.GetItemHandlesForDefinition(serverHandle, tagAddress);
for (int index = 0; index < candidates.Count; index++)
{
if (IsAdvised(serverHandle, candidates[index]))
{
itemHandle = candidates[index];
advised = true;
return true;
}
}
advised = false;
if (candidates.Count > 0)
{
itemHandle = candidates[0];
return true;
}
itemHandle = 0;
return false;
}
private static void PumpEvery(ref int calls, Action pumpStep)
{
if (calls > 0 && calls % ReadBulkPumpInterval == 0)
@@ -1209,12 +1351,11 @@ public sealed class MxAccessSession : IDisposable
{
int candidate = candidates[index];
if (!handleRegistry.ContainsAdviceHandle(serverHandle, candidate, MxAccessAdviceKind.Plain)
&& !handleRegistry.ContainsAdviceHandle(serverHandle, candidate, MxAccessAdviceKind.Supervisory))
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.
// path, which advises this handle temporarily.
continue;
}
@@ -1597,15 +1738,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 waits on: the caller's
/// registered handle when phase 1 found one, otherwise 0 until
/// ReadBulk's 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 the wait compares against:
/// captured before ReadBulk's Advise, or in phase 1 for a handle the
/// caller already advised.
/// </summary>
public ulong Baseline { get; set; }
/// <summary>Gets or sets a value indicating whether Advise succeeded.</summary>
/// <summary>Gets or sets a value indicating whether <see cref="Baseline"/> has been captured.</summary>
public bool BaselineCaptured { get; set; }
/// <summary>Gets or sets a value indicating whether ReadBulk itself advised the handle (phase 4 unadvises it).</summary>
public bool Advised { get; set; }
/// <summary>
/// Gets or sets a value indicating whether ReadBulk's own AddItem
/// created the item (phase 4 removes it). False for a handle the
/// caller held before this call.
/// </summary>
public bool OwnsItem { get; set; }
/// <summary>
/// Gets or sets the earlier snapshot in the same batch whose
/// subscription this one shares (same item handle), or null.