fix(opcua): replay writes deferred during an off-thread plan; cache-ref and guard fixes (Lane B fix round 1)

C1 (critical): B6 computes the plan off the pinned thread while B1 made writes
non-creating, so a value/status/alarm write for a node the in-flight plan adds
was skipped, and change-driven drivers never republish it (BadWaitingForInitialData
indefinitely; on a full rebuild every re-subscribe value landed on discarded
nodes). OpcUaPublishActor now applies writes immediately AND remembers the
latest per (realm, id) while a plan is in flight or queued (value+status
compose; alarm state/quality coalesce to the latest, which the node's delta
gate makes inert on an existing condition), replays it after each apply before
answering, and drops it once the pipeline is idle. Bounded (250k keys by
default; beyond it new keys are not held, logged once).

I2: the data-plane-authority parse runs in its own try inside the plan task; a
throw is logged and never degrades the address-space apply.

I3: the SDK's DeleteMonitoredItems releases an item's component-cache
reference on a Good delete; a tombstoned item's reference was already
released, so the delete took one from the re-created node's entry. Released
items are remembered and the orphan delete takes one back first. Event items
never held a reference (EventManager + SubscribeToEvents), so the three
event-item releases are gone.

I4: direct tests for the HistoryUpdate override's per-request updater check
and the HistoryReadEvents override's source guard (both reached by restoring
the bit after a reset - the B7 race window); fixed the false remark.

Minors: the MaterialiseAlarmCondition kind-swap tombstones the dropped
instance; a bytes-less rebuild arriving mid-plan queues behind it (replies in
order); a PlanReady/PlanFailed from a previous actor incarnation is ignored and
its requester answered degraded; the tie-cluster end bound of an uncapped read
fits against the backend ceiling (defence in depth - guarded by a sweep test);
the lock-time benchmark stays in the default run, headroom noted.

Refs #732
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
Joseph Doherty
2026-10-22 14:30:11 -04:00
parent 7c7ecff974
commit f966efcfad
9 changed files with 977 additions and 30 deletions
@@ -1494,6 +1494,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
// same-key kind-swap ever carries wired notifiers), but this is the one asymmetric teardown
// path; keep it symmetric with RemoveAlarmConditionNode / RebuildAddressSpace.
UnwireAlarmNotifiers(conditionKey);
// A removal path like any other (review 01 L2): the dropped instance's items are told and its
// fan-out forgotten, or a new item on the swapped-in condition would bind to the dead one.
TombstoneMonitoredSubtree(existing, UtcNow);
existing.Parent?.RemoveChild(existing);
ForgetPredefinedSubtree(existing);
// The materialise tail raises only the new instance's unit (no full reconcile), so give the
@@ -4413,6 +4416,18 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
|| current.DataChangeMonitoredItems?.Contains(dataItem) != true))
{
OnMonitoredItemDeleted(context, handle, dataItem);
// Review fix I3 — the SDK's DeleteMonitoredItems releases the item's component-cache reference
// whenever this returns Good. A tombstoned item's reference was ALREADY released by the removal, so
// that second release would take one from the RE-CREATED node's entry (a new item on the same NodeId)
// and evict it while still referenced. Take one back first so the SDK's release nets to zero —
// returning a non-Good status instead would fail the client's delete.
if (_cacheReferenceReleased.TryGetValue(dataItem, out _))
{
_cacheReferenceReleased.Remove(dataItem);
AddNodeToComponentCache(context, handle, handle.Node);
}
return ServiceResult.Good;
}
}
@@ -4472,11 +4487,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
if (monitored.EventMonitoredItems is { Count: > 0 } eventItems)
{
foreach (var item in eventItems.ToArray())
{
_eventItems.TryRemove(item, out _);
ReleaseComponentCacheReference(item);
}
// No component-cache release: an event item never took a reference (the master node manager
// creates it through the EventManager + SubscribeToEvents, not AddNodeToComponentCache), so a
// release here would take one from a DATA item on the same NodeId.
foreach (var item in eventItems.ToArray()) _eventItems.TryRemove(item, out _);
}
}
@@ -4534,7 +4548,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
if (!tracked.Suppressed || (nodeId is not null && tracked.Handle.NodeId != nodeId)) continue;
if (!_eventItems.TryRemove(item, out _)) continue;
Interlocked.Decrement(ref _suppressedItems);
ReleaseComponentCacheReference(item);
// Event items hold no component-cache reference (see TombstoneMonitoredNode).
}
}
@@ -4555,13 +4569,21 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
}
}
/// <summary>Gives back the component-cache reference the SDK took for <paramref name="item"/> at create, so
/// the cache stops handing out the removed node for that NodeId.</summary>
/// <summary>Gives back the component-cache reference the SDK took for the DATA item <paramref name="item"/> at
/// create, so the cache stops handing out the removed node for that NodeId — and remembers that it did, so the
/// item's later client delete does not give it back a second time (see <see cref="DeleteMonitoredItem"/>).</summary>
private void ReleaseComponentCacheReference(IMonitoredItem item)
{
if (item.ManagerHandle is NodeHandle handle) RemoveNodeFromComponentCache(SystemContext, handle);
if (item.ManagerHandle is not NodeHandle handle) return;
RemoveNodeFromComponentCache(SystemContext, handle);
_cacheReferenceReleased.AddOrUpdate(item, ReleasedMarker);
}
/// <summary>Data items whose component-cache reference a removal already gave back (review fix I3). Weak, so an
/// item the SDK drops without a delete (it always deletes, but a leak here would be silent) is not kept alive.</summary>
private readonly System.Runtime.CompilerServices.ConditionalWeakTable<IMonitoredItem, object> _cacheReferenceReleased = new();
private static readonly object ReleasedMarker = new();
/// <summary>Test observability: how many NodeIds currently carry a <see cref="MonitoredNode2"/> fan-out.</summary>
internal int MonitoredNodeCount
{
@@ -5352,8 +5374,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
{
_eventItems.TryRemove(item, out _);
Interlocked.Decrement(ref _suppressedItems);
ReleaseComponentCacheReference(item);
continue;
continue; // an event item holds no component-cache reference (see TombstoneMonitoredNode)
}
SubscribeToEvents(SystemContext, tracked.Handle.Node, item, unsubscribe: !permitted);
@@ -7065,7 +7086,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
else if (endBound is not null)
{
// The data is drained — the end bound ends this page, or is the next one when this one is full.
clusterCp = await AppendEndBoundAsync(slice, startUtc, readCap).ConfigureAwait(false);
// An uncapped read (readCap 0) on a backend with a row ceiling is still a page of at most that
// ceiling — the MaxReturnDataValues it advertises — so the bound fits against it, not "unbounded".
// (Today the over-fetch bound keeps a cluster slice at most L − 1, so this is defence in depth.)
var clusterAllowance = readCap > 0 ? readCap : pageLimit > 0 ? (uint)pageLimit : 0u;
clusterCp = await AppendEndBoundAsync(slice, startUtc, clusterAllowance).ConfigureAwait(false);
}
results[handle.Index] = new SdkHistoryReadResult