From e934854a89e5381bb684e3540b0d1b884f123537 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 21 Nov 2026 16:49:37 -0500 Subject: [PATCH] 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. --- .../MxGatewaySession.cs | 7 +- clients/go/mxgateway/session.go | 7 +- .../ww/mxgateway/client/MxGatewaySession.java | 6 +- .../python/src/zb_mom_ww_mxgateway/session.py | 8 +- clients/rust/src/session.rs | 7 +- docs/Contracts.md | 11 +- docs/DesignDecisions.md | 16 +- docs/MxAccessWorkerInstanceDesign.md | 23 +- gateway.md | 21 +- .../MxAccess/MxAccessSessionTests.cs | 210 +++++++++++++++++ .../MxAccess/MxAccessSession.cs | 213 +++++++++++++++--- 11 files changed, 470 insertions(+), 59 deletions(-) diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs index 2f7feb1c..2afac9ef 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs @@ -634,8 +634,11 @@ public sealed class MxGatewaySession : IAsyncDisposable /// /// Bulk Read — snapshot the current value for each requested tag. /// Returns the cached OnDataChange value when the tag is already advised - /// (WasCached = true), otherwise the worker takes the full AddItem + - /// Advise + wait + UnAdvise + RemoveItem snapshot lifecycle. Per-tag + /// (WasCached = true). Otherwise the worker waits for the first + /// OnDataChange: through the session's own item when the tag is already + /// added (advised temporarily if needed, never removed), or through the + /// full AddItem + Advise + wait + UnAdvise + RemoveItem snapshot lifecycle + /// when it is not. Per-tag /// failures (timeout, invalid tag) appear as /// entries with WasSuccessful = false; the call never throws on /// per-tag errors. diff --git a/clients/go/mxgateway/session.go b/clients/go/mxgateway/session.go index 89f1fb2e..b2a0223c 100644 --- a/clients/go/mxgateway/session.go +++ b/clients/go/mxgateway/session.go @@ -548,9 +548,10 @@ func (s *Session) WriteSecured2Bulk(ctx context.Context, serverHandle int32, ent // ReadBulk snapshots the current value of each requested tag. // // MXAccess COM has no synchronous Read; the worker satisfies this by returning the -// most recent cached OnDataChange value when the tag is already advised (WasCached=true), -// or by taking a full AddItem + Advise + wait + UnAdvise + RemoveItem snapshot lifecycle -// otherwise. timeout is one shared deadline for the whole command, not a per-tag budget: +// most recent cached OnDataChange value when the tag is already advised (WasCached=true). +// Otherwise it waits for the first OnDataChange: through the session's own item when the +// tag is already added (advised temporarily if needed, never removed), or through a full +// AddItem + Advise + wait + UnAdvise + RemoveItem snapshot lifecycle when it is not. timeout is one shared deadline for the whole command, not a per-tag budget: // the worker advises every uncached tag, waits once for all of them, then tears them down. // Pass zero to use the worker default (1000 ms). Per-tag failures (timeout, invalid tag) appear as BulkReadResult entries // with WasSuccessful=false; the call never returns an error for per-tag MXAccess failures. diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java index 320088ba..b0fd0afa 100644 --- a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java +++ b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java @@ -554,8 +554,10 @@ public final class MxGatewaySession implements AutoCloseable { *

MXAccess COM has no synchronous read; the worker returns the cached * {@code OnDataChange} value for any tag that is already advised * ({@code wasCached == true}) without modifying the existing subscription, - * and falls back to a full AddItem + Advise + wait + UnAdvise + RemoveItem - * snapshot lifecycle otherwise. The supplied {@code timeout} is one shared + * Otherwise it waits for the first {@code OnDataChange}: through the + * session's own item when the tag is already added (advised temporarily if + * needed, never removed), or through a full AddItem + Advise + wait + + * UnAdvise + RemoveItem snapshot lifecycle when it is not. The supplied {@code timeout} is one shared * deadline for the whole command, not a per-tag budget: the worker advises * every uncached tag, waits once for all of them, then tears them down. * Pass {@link Duration#ZERO} (or {@code null}) to use the worker default diff --git a/clients/python/src/zb_mom_ww_mxgateway/session.py b/clients/python/src/zb_mom_ww_mxgateway/session.py index f2a40f32..90c8b066 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/session.py +++ b/clients/python/src/zb_mom_ww_mxgateway/session.py @@ -452,9 +452,11 @@ class Session: MXAccess COM has no synchronous read; the worker returns the cached ``OnDataChange`` value for any tag that is already advised (``was_cached = - True``) without modifying the existing subscription, and falls back to - a full AddItem + Advise + wait + UnAdvise + RemoveItem snapshot lifecycle - otherwise. ``timeout_ms`` is one shared deadline for the whole command, + True``) without modifying the existing subscription. Otherwise it waits + for the first ``OnDataChange``: through the session's own item when the + tag is already added (advised temporarily if needed, never removed), or + through a full AddItem + Advise + wait + UnAdvise + RemoveItem snapshot + lifecycle when it is not. ``timeout_ms`` is one shared deadline for the whole command, not a per-tag budget: the worker advises every uncached tag, waits once for all of them, then tears them down. Pass ``0`` to use the worker default (1000 ms). diff --git a/clients/rust/src/session.rs b/clients/rust/src/session.rs index dcd7ef2f..cc033084 100644 --- a/clients/rust/src/session.rs +++ b/clients/rust/src/session.rs @@ -531,8 +531,11 @@ impl Session { /// /// MXAccess COM has no synchronous `Read`; the worker satisfies this by /// returning the most recent cached `OnDataChange` value when the tag is - /// already advised (`was_cached = true`), or by taking a full AddItem + - /// Advise + wait + UnAdvise + RemoveItem snapshot lifecycle otherwise. + /// already advised (`was_cached = true`). Otherwise it waits for the first + /// `OnDataChange`: through the session's own item when the tag is already + /// added (advised temporarily if needed, never removed), or through a full + /// AddItem + Advise + wait + UnAdvise + RemoveItem snapshot lifecycle when + /// it is not. /// `timeout_ms` is one shared deadline for the whole command, not a /// per-tag budget: the worker advises every uncached tag, waits once for /// all of them, then tears them down. `timeout_ms == 0` lets the worker diff --git a/docs/Contracts.md b/docs/Contracts.md index d784ddb7..12ec8736 100644 --- a/docs/Contracts.md +++ b/docs/Contracts.md @@ -90,10 +90,13 @@ 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 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` + - `RemoveItem` snapshot lifecycle and returns the result - (`was_cached = false`). The asymmetry that `BulkReadResult` has no + (`was_cached = true`); otherwise it returns the first `OnDataChange` it + observes (`was_cached = false`) — through the session's own subscription + for an advised tag with no value yet, through a temporary advise of the + session's own item for an added-but-unadvised tag, or through a full + `AddItem` + `Advise` + wait + `UnAdvise` + `RemoveItem` snapshot + lifecycle for a tag the session never added. It never unadvises or + removes anything the session created. The asymmetry that `BulkReadResult` has no `hresult` field is intentional — `ReadBulk` outcomes are timeout / cache / lifecycle states rather than MXAccess COM return codes. diff --git a/docs/DesignDecisions.md b/docs/DesignDecisions.md index 45d8fbd2..3a82cbb6 100644 --- a/docs/DesignDecisions.md +++ b/docs/DesignDecisions.md @@ -529,10 +529,20 @@ choices were considered: 1. **Cache-then-snapshot** (chosen): when a requested tag is already in the session's item registry AND advised, the worker returns the last cached `OnDataChange` value without touching the subscription - (`was_cached = true`). Otherwise it takes the full `AddItem + Advise + - wait-for-first-OnDataChange + UnAdvise + RemoveItem` lifecycle itself + (`was_cached = true`). Otherwise it waits for the first `OnDataChange` (`was_cached = false`) and leaves the session exactly as it was before - the call. The cache lives on a per-session `MxAccessValueCache`, + the call: a tag the session advised but has no value for yet is waited + on through the session's own subscription; a tag the session added but + did not advise is advised on the session's own item handle and + unadvised afterwards; only a tag the session never added takes the full + `AddItem + Advise + wait + UnAdvise + RemoveItem` lifecycle. Reusing the + session's handle rather than adding a second item matters because the + snapshot teardown must never be able to reach an item or advice the + caller created (#238). The installed MXAccess hands out a distinct + handle per `AddItem` even for an address already added (verified live + on the dev rig, 2026-11-21), so a separate snapshot item does not + disturb the caller's today; the reuse also saves an extra item and four + COM calls per tag. The cache lives on a per-session `MxAccessValueCache`, populated by `MxAccessBaseEventSink` on every `OnDataChange` after the event clears the outbound queue. diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md index d61354d8..d91394fa 100644 --- a/docs/MxAccessWorkerInstanceDesign.md +++ b/docs/MxAccessWorkerInstanceDesign.md @@ -355,18 +355,29 @@ 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 cached-and-advised fast path, and a tag the session +already added is resolved to the session's own item handle; (2) every +remaining tag gets an advised handle to wait on — the session's advised +handle is used as is, the session's unadvised handle is advised +temporarily, and only a tag the session never added gets ReadBulk's own +`AddItem` and `Advise`; (3) one wait with a shared deadline collects the +first `OnDataChange` per handle and returns as soon as all have delivered; +(4) ReadBulk undoes only what phase 2 did, best-effort: it unadvises the +advices it made and removes the items it added, never the session's own +item or advice (#238). A session handle ReadBulk advised temporarily also +has its cached value dropped on unadvise, so a later `Advise` + `ReadBulk` +cannot serve that snapshot as `was_cached = true`. The baseline for a +session-advised handle is taken in phase 1, before any phase-2 pump can +dispatch its first `OnDataChange`, so that value still satisfies the read. 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 ms waiting for first OnDataChange.` message for each tag that never delivered. The cache probes all run before any snapshot `AddItem`, so a later tag in the same request can never be served from an earlier tag's snapshot subscription. -When MXAccess returns the same item handle for two tags in one batch (a -duplicate address), the handle is advised, unadvised, and removed once, and +When two tags in one batch resolve to the same item handle (a duplicate +address of a session item, or an `AddItem` that returns a handle already in +play), the handle is advised, unadvised, and removed at most once, and every duplicate receives the shared outcome. Phases 2 and 4 make one or two COM calls per tag without waiting, so they call the pump step every `ReadBulkPumpInterval` (16) tags; a large batch therefore keeps dispatching diff --git a/gateway.md b/gateway.md index 290b39ef..6b0b4412 100644 --- a/gateway.md +++ b/gateway.md @@ -570,14 +570,21 @@ returns one result per requested entry — per-entry failures populate `BulkReadReply` (`repeated BulkReadResult`). MXAccess COM has no synchronous `Read`; the worker satisfies this command by returning the 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 + advised (`was_cached = true`, no subscription side-effects); otherwise it + waits for the first `OnDataChange` (`was_cached = false`). How it gets + that value depends on what the session already holds for the address: + a tag the session advised but has no value for yet is waited on through + the session's own subscription, with no COM call; a tag the session + added but did not advise is advised on the session's own item handle + and unadvised afterwards, the item kept; any other tag takes a full + `AddItem` + `Advise` + wait + `UnAdvise` + `RemoveItem` snapshot + lifecycle. ReadBulk never unadvises or removes an item or advice the + session created (#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 - add/advise and teardown COM calls, during which it pumps every 16 tags). + every uncached tag first, waits once for all of them, then undoes its + own adds and advises, 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 addresses that MXAccess resolves to the same item handle share one diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessSessionTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessSessionTests.cs index 0e619068..167159b4 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessSessionTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessSessionTests.cs @@ -428,6 +428,216 @@ public sealed class MxAccessSessionTests Assert.Contains(pumpAtOperation, at => at > firstUnAdvise); } + ///

+ /// #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. + /// + [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); + } + + /// + /// 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. + /// + [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 results = session.ReadBulk(serverHandle, tags, TimeSpan.FromMilliseconds(100), pumpStep); + + Assert.True(results[0].WasSuccessful, results[0].ErrorMessage); + Assert.Equal(9, results[0].Value.Int32Value); + } + + /// + /// #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 + /// was_cached = true. + /// + [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 _)); + } + + /// + /// 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. + /// + [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); + } + + /// + /// #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. + /// + [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 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 statuses = new() { new MxStatusProxy { Category = MxStatusCategory.Ok } }; diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs index c3c37b38..72f0af33 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs @@ -927,8 +927,13 @@ public sealed class MxAccessSession : IDisposable /// /// 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. /// bounds the wait for every snapshot tag; /// 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 waiting = new(snapshots.Count); - Dictionary advisedByHandle = new(); + Dictionary waitingByHandle = new(); List 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 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 unadvised = new(); HashSet 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 } } + /// + /// 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. + /// + 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); + } + + /// + /// 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). + /// + private bool TryGetRegisteredHandleFor( + int serverHandle, + string tagAddress, + out int itemHandle, + out bool advised) + { + IReadOnlyList 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 /// Gets the requested tag address. public string TagAddress { get; } - /// Gets or sets the snapshot item handle, 0 until AddItem succeeds. + /// + /// 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. + /// public int ItemHandle { get; set; } - /// Gets or sets the value-cache version captured before Advise. + /// + /// 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. + /// public ulong Baseline { get; set; } - /// Gets or sets a value indicating whether Advise succeeded. + /// Gets or sets a value indicating whether has been captured. + public bool BaselineCaptured { get; set; } + + /// Gets or sets a value indicating whether ReadBulk itself advised the handle (phase 4 unadvises it). public bool Advised { get; set; } + /// + /// 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. + /// + public bool OwnsItem { get; set; } + /// /// Gets or sets the earlier snapshot in the same batch whose /// subscription this one shares (same item handle), or null.