fix(worker): forget write-completion entries for dropped ack item handles

Add MxAccessWriteCompletionCache.Remove and RemoveServer and call them
from AlarmAckWriter when it drops an item (dirty re-add, LRU eviction,
failed AddItem/Advise/Write) and when it tears down its registration, so
the cache no longer keeps one entry per dropped handle for the life of
the worker.

Fixes #165

Claude-Session: https://claude.ai/code/session_016J6isfcgqy4SB2RK3ZvFvT
This commit is contained in:
Joseph Doherty
2026-10-20 07:09:59 -04:00
parent 219611c821
commit f13950e453
5 changed files with 172 additions and 0 deletions
@@ -303,6 +303,9 @@ public sealed class AlarmAckWriter : IAlarmAckWriter
try { mx.Unregister(serverHandle); } catch { /* best effort */ }
}
// The registration is gone, so no completion can arrive for its handles.
completionCache.RemoveServer(serverHandle);
itemHandles.Clear();
itemLru.Clear();
server = null;
@@ -335,6 +338,10 @@ public sealed class AlarmAckWriter : IAlarmAckWriter
itemLru.Remove(node);
try { mx.UnAdvise(serverHandle, node.Value.Handle); } catch { /* best effort */ }
try { mx.RemoveItem(serverHandle, node.Value.Handle); } catch { /* best effort */ }
// Without this the completion cache keeps one entry per dropped handle
// (each Unconfirmed re-add and each eviction) for the worker's life.
completionCache.Remove(serverHandle, node.Value.Handle);
}
private IMxAccessServer EnsureRegistered()
@@ -184,6 +184,57 @@ public sealed class MxAccessWriteCompletionCache
}
}
/// <summary>
/// Forgets the completion entry of a handle pair whose MXAccess item was
/// removed, so a long-lived writer that drops and re-adds items does not
/// keep one entry per dropped handle for the life of the worker.
/// </summary>
/// <param name="serverHandle">MXAccess server handle.</param>
/// <param name="itemHandle">MXAccess item handle that was removed.</param>
public void Remove(
int serverHandle,
int itemHandle)
{
lock (syncRoot)
{
entries.Remove(CreateItemKey(serverHandle, itemHandle));
}
}
/// <summary>Forgets every completion entry recorded under a server handle that was unregistered.</summary>
/// <param name="serverHandle">MXAccess server handle that was unregistered.</param>
public void RemoveServer(int serverHandle)
{
lock (syncRoot)
{
List<long> stale = new();
foreach (long key in entries.Keys)
{
if ((int)(key >> 32) == serverHandle)
{
stale.Add(key);
}
}
foreach (long key in stale)
{
entries.Remove(key);
}
}
}
/// <summary>Gets the number of handle pairs with a recorded completion (test seam).</summary>
internal int Count
{
get
{
lock (syncRoot)
{
return entries.Count;
}
}
}
private static long CreateItemKey(
int serverHandle,
int itemHandle)