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.
This commit is contained in:
Joseph Doherty
2026-12-01 19:38:11 -05:00
parent 2e6645ef92
commit cc33b063fa
7 changed files with 154 additions and 107 deletions
+4 -5
View File
@@ -90,11 +90,10 @@ of items per round trip while preserving MXAccess parity per entry.
synchronous `Read`, so `ReadBulk` is dual-mode per entry: when a tag is
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` +
(`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` +
`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
+18 -16
View File
@@ -534,19 +534,21 @@ choices were considered:
(`was_cached = false`) and leaves the session exactly as it was before
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`,
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
event clears the outbound queue.
@@ -562,9 +564,9 @@ The decision intentionally does NOT synthesize an `OnDataChange` event
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
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
+16 -15
View File
@@ -356,18 +356,20 @@ 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 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
remaining tag gets an advised handle — a tag the caller has advised keeps the
caller's item handle and its existing subscription, any other tag gets the
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
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
@@ -750,9 +752,8 @@ 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 (for example the value a `ReadBulk`'s own temporary advice on a
caller's added-only item captured) before the new advice's first
`OnDataChange` lands. Failed advice and cleanup calls
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
successful MXAccess-owned state transition.
+8 -9
View File
@@ -570,15 +570,14 @@ 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 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
`UnAdvise` + `RemoveItem` snapshot lifecycle otherwise
(`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
every tag that needs it first, waits once for all of them, then tears
@@ -648,14 +648,16 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
}
/// <summary>
/// Issue #238 live repro: a <c>ReadBulk</c> of a tag the client already holds must not
/// tear down the client's item or subscription. Step 1 reads an added-but-not-advised
/// item (deterministic: it is never cached), after which the client must still be able
/// to advise its own handle. Step 2 reads the tag right after that advise — the window a
/// subscribe-then-seed-read client hits, where the first OnDataChange may not be cached
/// yet — and then proves the subscription still delivers by writing a fresh value and
/// waiting for its OnDataChange. Before the fix, either read could unadvise and remove
/// the client's item, so the advise failed or the written value never arrived.
/// 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]
@@ -714,7 +716,8 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
// Step 1: added but not advised.
BulkReadResult addedOnlyRead = await ReadBulkSingleAsync(fixture, sessionId, serverHandle, "added-only").ConfigureAwait(false);
Assert.True(addedOnlyRead.WasSuccessful, addedOnlyRead.ErrorMessage);
Assert.Equal(itemHandle, addedOnlyRead.ItemHandle);
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);
@@ -433,9 +433,8 @@ public sealed class MxAccessSessionTests
/// 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.
/// 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()
@@ -495,12 +494,58 @@ public sealed class MxAccessSessionTests
}
/// <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.
/// 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_AdvisesForTheReadThenUnAdvisesButNeverRemovesTheCallersItem()
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();
@@ -525,7 +570,12 @@ public sealed class MxAccessSessionTests
Assert.Equal(callerHandle, result.ItemHandle);
Assert.Equal(17, result.Value.Int32Value);
Assert.Equal(
new[] { $"Advise:{serverHandle}:{callerHandle}", $"UnAdvise:{serverHandle}:{callerHandle}" },
new[]
{
$"AddItem:{serverHandle}:Tag.AddedOnly",
$"Advise:{serverHandle}:{callerHandle}",
$"UnAdvise:{serverHandle}:{callerHandle}",
},
server.Operations.Skip(operationsBeforeRead));
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.AddedOnly", expectAdvised: false);
}
@@ -554,8 +604,9 @@ public sealed class MxAccessSessionTests
/// <summary>
/// The value a ReadBulk's temporary advice on a caller's added-only item
/// produced must not be served as cached once the caller advises the
/// item itself: the next read waits for the caller's own first value.
/// 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()
@@ -643,7 +694,8 @@ public sealed class MxAccessSessionTests
/// 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.
/// 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()
@@ -686,6 +738,7 @@ public sealed class MxAccessSessionTests
Assert.Equal(
new[]
{
$"AddItem:{serverHandle}:Tag.AddedOnly",
$"Advise:{serverHandle}:{addedOnly}",
$"AddItem:{serverHandle}:Tag.Fresh",
$"Advise:{serverHandle}:{fresh}",
@@ -961,18 +961,20 @@ public sealed class MxAccessSession : IDisposable
/// 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.
/// 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>
/// <param name="serverHandle">The MXAccess server handle.</param>
@@ -1005,8 +1007,9 @@ public sealed class MxAccessSession : IDisposable
// 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.
// 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++)
{
string? tagAddress = tagAddresses[index];
@@ -1028,7 +1031,7 @@ public sealed class MxAccessSession : IDisposable
}
SnapshotRead snapshot = new(index, tagAddress!);
if (existing != ExistingItemState.None)
if (existing == ExistingItemState.Advised)
{
snapshot.ItemHandle = existingItemHandle;
snapshot.IsCallerItem = true;
@@ -1109,9 +1112,10 @@ public sealed class MxAccessSession : IDisposable
}
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.
// 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;
}
}
@@ -1273,9 +1277,10 @@ public sealed class MxAccessSession : IDisposable
}
/// <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.
/// 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>
@@ -1284,7 +1289,7 @@ public sealed class MxAccessSession : IDisposable
/// <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>
/// <returns>The strongest state among the tag's advised items.</returns>
private ExistingItemState FindExistingItem(
int serverHandle,
string tagAddress,
@@ -1297,19 +1302,13 @@ public sealed class MxAccessSession : IDisposable
// 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,
// then the first advised one, then the first added one.
// then the first advised 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 (firstAdded == 0)
{
firstAdded = candidate;
}
if (!IsAdvised(serverHandle, candidate))
{
continue;
@@ -1328,14 +1327,8 @@ public sealed class MxAccessSession : IDisposable
}
cachedValue = default;
if (firstAdvised != 0)
{
itemHandle = firstAdvised;
return ExistingItemState.Advised;
}
itemHandle = firstAdded;
return firstAdded != 0 ? ExistingItemState.Added : ExistingItemState.None;
itemHandle = firstAdvised;
return firstAdvised != 0 ? ExistingItemState.Advised : ExistingItemState.None;
}
private bool IsAdvised(
@@ -1783,15 +1776,12 @@ public sealed class MxAccessSession : IDisposable
public SnapshotRead? SharedWith { get; set; }
}
/// <summary>What the session already holds for a ReadBulk tag before the read.</summary>
/// <summary>What the caller has advised 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>
/// <summary>No advised item for the tag: the read takes a snapshot AddItem.</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,