diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md index ac0f3248..74d80f53 100644 --- a/docs/MxAccessWorkerInstanceDesign.md +++ b/docs/MxAccessWorkerInstanceDesign.md @@ -793,13 +793,20 @@ caches the event sink fills: `RemoveItem` drops the handle pair's removes the server's items with it, so the per-item eviction never runs for them). Without this, an `AddItem` → `Write` → `RemoveItem` churn grew the completion cache by one entry per cycle for the life of the worker. -`AddItem`, `AddItem2`, and `AddBufferedItem` also drop both cache entries for -the handle they receive when the registry does not already track it. An -`OnDataChange` or `OnWriteComplete` that was queued when `RemoveItem` or -`Unregister` ran is dispatched after the eviction and recreates the entry; -when MXAccess later reuses that item id, `ReadBulk`'s cached path would -otherwise serve the stale value as `was_cached = true`. A handle the -registry still tracks belongs to a live item, so its entries are kept. Failed advice and cleanup calls +An `OnDataChange` or `OnWriteComplete` that was queued when `RemoveItem` or +`Unregister` ran is dispatched after the eviction. `MxAccessSession.Create` +binds the session's handle registry to the production event sink, and the sink +writes a cache entry only for an item handle the registry still holds; the +event itself is still forwarded to the gateway. Without the check the late +callback re-created the entry, and because MXAccess hands out strictly +increasing item handles within a registration, nothing evicted it again before +`Unregister`: a `ReadBulk` poll loop or subscribe/unsubscribe churn leaked one +entry per cycle in the 32-bit worker (MXA-004). As a backstop for a sink that is +not bound to a registry, `AddItem`, `AddItem2`, and `AddBufferedItem` also drop +both cache entries for the handle they receive when the registry does not +already track it, so a reused id never serves a stale value as +`was_cached = true`. A handle the registry still tracks belongs to a live item, +so its entries are kept. Failed advice and cleanup calls leave registry state unchanged so diagnostics continue to reflect the last successful MXAccess-owned state transition. diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessBaseEventSinkTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessBaseEventSinkTests.cs index da04caba..9f7628fb 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessBaseEventSinkTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessBaseEventSinkTests.cs @@ -95,6 +95,62 @@ public sealed class MxAccessBaseEventSinkTests Assert.Equal(timestamp, cached.SourceTimestamp.ToDateTime()); } + /// + /// MXA-004: an OnDataChange or OnWriteComplete that MXAccess had already + /// queued on the STA is dispatched after RemoveItem evicted the + /// handle. The unbound sink (see ) + /// records such a callback for any handle, which re-creates an entry nothing + /// evicts again because item handles are not reused within a registration. + /// Once bound to the session's registry, the sink must still forward the + /// event but leave both caches untouched for a removed handle. + /// + [Fact] + public void LateCallbacks_ForRemovedItemHandle_AreForwardedButNotCached() + { + MxAccessEventQueue queue = new(); + MxAccessValueCache cache = new(); + MxAccessWriteCompletionCache completionCache = new(); + MxAccessBaseEventSink sink = new(queue, new MxAccessEventMapper(), cache, completionCache); + MxAccessHandleRegistry registry = new(); + registry.RegisterServerHandle(7, "client"); + registry.RegisterItemHandle(7, 21, "Tag.A", string.Empty, hasItemContext: false); + sink.BindHandleRegistry(registry); + MXSTATUS_PROXY[] statuses = Array.Empty(); + + registry.RemoveItemHandle(7, 21); + sink.OnDataChange(7, 21, 1234, 192, new DateTime(2026, 5, 18, 9, 15, 0, DateTimeKind.Utc), ref statuses); + sink.OnWriteComplete(7, 21, ref statuses); + + Assert.Equal(2, queue.Count); + Assert.False(cache.TryGet(7, 21, out _)); + Assert.Equal(0UL, completionCache.CurrentVersion(7, 21)); + } + + /// + /// The registry check must not suppress caching for a handle the session + /// still holds. + /// + [Fact] + public void Callbacks_ForLiveItemHandle_AreCachedWhenRegistryBound() + { + MxAccessEventQueue queue = new(); + MxAccessValueCache cache = new(); + MxAccessWriteCompletionCache completionCache = new(); + MxAccessBaseEventSink sink = new(queue, new MxAccessEventMapper(), cache, completionCache); + MxAccessHandleRegistry registry = new(); + registry.RegisterServerHandle(7, "client"); + registry.RegisterItemHandle(7, 21, "Tag.A", string.Empty, hasItemContext: false); + sink.BindHandleRegistry(registry); + MXSTATUS_PROXY[] statuses = Array.Empty(); + + sink.OnDataChange(7, 21, 1234, 192, new DateTime(2026, 5, 18, 9, 15, 0, DateTimeKind.Utc), ref statuses); + sink.OnWriteComplete(7, 21, ref statuses); + + Assert.True(cache.TryGet(7, 21, out MxAccessValueCache.CachedValue cached)); + Assert.Equal(1234, cached.Value.Int32Value); + Assert.Equal(1UL, completionCache.CurrentVersion(7, 21)); + } + /// /// Verifies that the sink-bound ValueCache is exposed for sharing with /// the owning so writes and reads see the same diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessBaseEventSink.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessBaseEventSink.cs index 21d8e4b5..a40582b9 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessBaseEventSink.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessBaseEventSink.cs @@ -11,6 +11,7 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion private readonly MxAccessEventQueue eventQueue; private readonly MxAccessValueCache valueCache; private readonly MxAccessWriteCompletionCache writeCompletionCache; + private MxAccessHandleRegistry? handleRegistry; private LMXProxyServerClass? server; private string sessionId = string.Empty; @@ -88,6 +89,24 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion /// public MxAccessWriteCompletionCache WriteCompletionCache => writeCompletionCache; + /// + /// Binds the session's handle registry so the per-handle caches only + /// record callbacks for item handles the session still holds. MXAccess + /// can dispatch an OnDataChange or OnWriteComplete that + /// was already queued on the STA after RemoveItem evicted the + /// handle; without this check the callback re-creates the entry, and + /// because MXAccess never reuses an item handle within a registration, + /// nothing evicts it again before Unregister (MXA-004). The event + /// itself is still forwarded: the gateway relays every event MXAccess + /// raises. Registry and callbacks are both STA-only, so no lock is + /// needed. An unbound sink (unit tests) caches every callback. + /// + /// The owning session's handle registry. + internal void BindHandleRegistry(MxAccessHandleRegistry registry) + { + handleRegistry = registry ?? throw new ArgumentNullException(nameof(registry)); + } + /// public void Attach( object mxAccessComObject, @@ -153,7 +172,13 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion pwItemQuality, pftItemTimeStamp, statuses), - mxEvent => valueCache.Set(hLMXServerHandle, phItemHandle, mxEvent)); + mxEvent => + { + if (IsLiveItemHandle(hLMXServerHandle, phItemHandle)) + { + valueCache.Set(hLMXServerHandle, phItemHandle, mxEvent); + } + }); } /// @@ -180,7 +205,13 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion hLMXServerHandle, phItemHandle, statuses), - mxEvent => writeCompletionCache.Record(hLMXServerHandle, phItemHandle, mxEvent.Statuses)); + mxEvent => + { + if (IsLiveItemHandle(hLMXServerHandle, phItemHandle)) + { + writeCompletionCache.Record(hLMXServerHandle, phItemHandle, mxEvent.Statuses); + } + }); } /// @@ -235,6 +266,14 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion statuses)); } + private bool IsLiveItemHandle( + int serverHandle, + int itemHandle) + { + MxAccessHandleRegistry? registry = handleRegistry; + return registry is null || registry.ContainsItemHandle(serverHandle, itemHandle); + } + private void EnqueueEvent(Func createEvent) { EnqueueEvent(createEvent, postPublish: null); diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs index 72f0af33..d1b8c6db 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs @@ -159,9 +159,19 @@ public sealed class MxAccessSession : IDisposable // ReadBulk reads both see the same instance. Fall back to a fresh // cache for test fakes that supply their own sink — ReadBulk simply // never serves cached values in that case. - MxAccessValueCache valueCache = eventSink is MxAccessBaseEventSink baseSink - ? baseSink.ValueCache - : new MxAccessValueCache(); + MxAccessHandleRegistry handleRegistry = new(); + MxAccessValueCache valueCache; + if (eventSink is MxAccessBaseEventSink baseSink) + { + valueCache = baseSink.ValueCache; + // Late callbacks for removed handles must not re-create cache + // entries nothing would ever evict (MXA-004). + baseSink.BindHandleRegistry(handleRegistry); + } + else + { + valueCache = new MxAccessValueCache(); + } // Share the sink's completion cache the same way (the production // sink and completion-aware test sinks implement the provider @@ -176,7 +186,7 @@ public sealed class MxAccessSession : IDisposable mxAccessComObject, new MxAccessComServer(mxAccessComObject), eventSink, - new MxAccessHandleRegistry(), + handleRegistry, valueCache, writeCompletionCache, Environment.CurrentManagedThreadId); @@ -286,7 +296,9 @@ public sealed class MxAccessSession : IDisposable /// reused id would let ReadBulk's cached fast path serve that stale /// value as was_cached = true. A handle the registry still /// tracks is a live item (MXAccess returned an existing handle), so its - /// current entries are kept. + /// current entries are kept. The production sink now skips cache + /// writes for handles the registry no longer holds (MXA-004), so this + /// is the backstop for sinks that are not bound to the registry. /// private void EvictStaleHandleState( int serverHandle,