diff --git a/docs/DataConnections.md b/docs/DataConnections.md
index 3aa3ef51e..9ea4fab83 100644
--- a/docs/DataConnections.md
+++ b/docs/DataConnections.md
@@ -209,6 +209,53 @@ being committed, the replacement could send that newer value as a live delta bef
snapshot that followed then carried the older captured value. Now the change waits until the item's snapshot is
complete, and the item then delivers it as a live delta.
+### Scaling the projected subscription path (#994)
+
+These behaviours changed in #994 (review 2026-12-02 Wave 3). They matter when a consumer holds many projected monitored
+items or an origin is busy.
+
+- **A cohort holds more than one item.** A cohort is the consumer's one stream per connection, serving identity and
+ publishing interval. Its `OpenSubscription` used to declare a snapshot budget of 1 item. The origin sizes the stream's
+ handle table from that budget, so it refused the second item `LimitExceeded`. The consumer then dropped and re-opened
+ the stream in a loop. In practice two projected items with the same interval broke each other. The open now declares
+ the consumer's `MaxMonitoredItems`.
+- **Opens, adds and removes are batched.** A cohort used to send one command per item. The origin admits 128 commands per
+ second per principal and stops the session past that, so any cohort of more than about 128 items never came back after
+ a reconnect. Commands now carry up to the peer's batch limit (`IDataSubscriptionCommandLimits`, at most 256 items,
+ bounded by the estimated snapshot bytes). Each cohort also paces itself (32 commands burst, 32 per second, at most 4
+ awaiting acknowledgement). A 10k-item cohort opens in about 80 commands, including the freshness challenges.
+- **One removal never tears down its siblings.** Control events (add, remove, refresh, renewal) no longer share the bounded
+ frame queue. When that queue was full, a failed `Remove` stopped the cohort and disposed every demand on it. Frames keep
+ their backpressure through a separate slot count.
+- **Local publish capacity is backpressure.** A sample the local SDK sink refuses because its pending bytes are full is
+ retried for up to 2 s. Before, this invalidated healthy evidence, retired the route and forced a re-snapshot. After the
+ 2 s bound the old fail-closed behaviour applies (`IProjectedValuePublisher.TryPublishOrBackpressure`).
+- **A per-call failure no longer backs off the connection.** Only an endpoint that could not be *selected* arms the
+ discovery backoff. A cancelled or failed unary call (Read, GetMetadata, Browse) after a successful selection fails that
+ call alone. A caller's cancel now surfaces as `OperationCanceledException`. Before, any such failure refused every other
+ subscribe, write and read on the connection for at least 250 ms ("Data endpoint discovery is backing off").
+- **Origin: a busy node no longer resets quiet streams.** A session used to scan at most 32 partition changes per tick,
+ counting other sources' changes too. It also reset when the 1024-entry change history rolled past its cursor. On a node
+ publishing thousands of changes per second, a stream with a few slow items reset again and again with "Source change
+ history expired.". Now unrelated changes do not consume the budget, and a lagging stream re-queues its tick. A cursor that
+ fell off the history catches up from each own source's last-change version, so it does not reset.
+- **Origin: one source's invalidation resets only its own streams.** A sibling source's invalidation, including plain lock
+ contention while publishing, used to reset every stream on the partition. A partition-wide invalidation still resets
+ them all.
+- **Origin: the publish authorization is memoised.** The publish check runs on every delivered frame. It is now memoised
+ for the exact catalog instance and authority generation, for at most 1 s. Any deployment or authority publish misses the
+ memo, so revoking a grant or key is still immediate. The commit under the session lock re-checks only identity.
+- **Smaller fixes.** The write-operation registry no longer copies its table on every claim. A history chunk saved into a
+ session cleared mid-request is refused, so its bytes are not charged until restart. A `Modify` deferred behind a snapshot
+ can no longer stall until its acknowledgement timeout. The condition stream's teardown no longer hides the real failure
+ behind `NotSupportedException`.
+- **Consumer node manager.** A projected publish looks up only that node's monitored items. It used to snapshot and
+ type-test every live item on the server, per value, under `Lock`. Eviction at the projected-node cap is linear (a
+ per-parent child count). Removing a projected anchor, or swapping it for a root leaf, now also tombstones the anchor's
+ own monitored node. Removing an imported condition purges only its own cached verdicts.
+
+Perf harness: `GrpcDataWave3PerfTests` (`Category=Perf`, opt-in `OTOPCUA_GRPCDATA_PERF=1`).
+
### Mixed versions (X0 rollout)
The remote history and alarm work (`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`)
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs
index f2c9c7f54..d5c6b9aa8 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs
@@ -149,6 +149,16 @@ public interface IDataSubscriptionFreshnessSupport
int FreshnessMaxItems { get; }
}
///
+/// #994 (R-2): the most items one command on this stream may carry (the peer's advertised batch limit, intersected with
+/// every local wrapper's own cap). A consumer batches its opens/adds/removes up to it instead of sending one command per
+/// item — the origin admits a bounded number of commands per second per principal and stops the stream past it.
+/// 0 means unknown (the caller uses its own conservative default).
+///
+public interface IDataSubscriptionCommandLimits
+{
+ int MaxCommandItems { get; }
+}
+///
/// A3 (review r1, deviation 9): a connection that can open a subscription served by the origin's Primary only —
/// condition items are served by the Primary (a Secondary advertises the feature but refuses the item, A2 N7), so the
/// consumer's condition stream must not land on a ReadyReplica Secondary the v1 value path would accept.
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
index a6c2eb2db..237348dda 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
@@ -787,7 +787,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
Volatile.Read(ref _refreshesInFlight));
Volatile.Read(ref _dataPlaneAuthority).Changed -= OnAuthorityChanged;
foreach (var item in _liveItems.Keys.OfType()) item.Retire();
- _liveItems.Clear();
+ LiveClear();
_eventItems.Clear();
_allEventsItems.Clear();
lock (Lock) _allEventsMonitoredConditions.Clear();
@@ -4436,6 +4436,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
}
OnProjectedFolderRemoving(nodeId);
+ // #994 (U-11): the anchor's OWN monitored node too, not only its descendants'. The SDK keys MonitoredNodes by NodeId
+ // and reuses an entry, so an event/attribute item left on the dead folder would capture every later item on the
+ // re-created anchor (delivery requires ReferenceEquals(monitored.Node, node)).
+ TombstoneMonitoredNode(nodeId, UtcNow);
_projectedAnchors.TryRemove(nodeId, out _);
_projectedRootLeaves.TryRemove(nodeId, out _);
RetireProjectedCharge(nodeId, anchor.Definition.Lifetime);
@@ -4558,7 +4562,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var pair in _projectedDefinitions.ToArray())
{
if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) ||
- _projectedVariables.Values.Any(child => child.Parent == pair.Key) || !pair.Value.Lifetime.TryRetire()) continue;
+ _projectedVariables.HasChildren(pair.Key) || !pair.Value.Lifetime.TryRetire()) continue;
if (!_projectedVariables.Remove(pair.Key, out var entry)) continue;
OnProjectedFolderRemoving(pair.Key);
_projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key);
@@ -4570,7 +4574,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var pair in _projectedAnchors.ToArray())
{
if (pair.Value.Definition.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) ||
- _projectedVariables.Values.Any(node => node.Parent == pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue;
+ _projectedVariables.HasChildren(pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue;
if (!_projectedAnchors.TryRemove(pair.Key, out var anchor)) continue;
OnProjectedFolderRemoving(pair.Key);
if (_projectedRootLeaves.TryRemove(pair.Key, out _))
@@ -4797,8 +4801,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
var source = target.Value.Snapshot.Value;
var detached = target.Value with { Snapshot = target.Value.Snapshot with { Value = source is Array array ? array.Clone() : source } };
- foreach (var item in _liveItems.Keys.OfType())
- if (item.ProjectedNodeId == target.Id && item.ObserveSample(detached)) snapshotRequests.Add(item);
+ // #994 (U-10): only this node's projected items — not a snapshot + type test of every live item
+ // on every namespace, per published value, under Lock.
+ foreach (var item in ProjectedLiveItemsFor(target.Id))
+ if (item.ObserveSample(detached)) snapshotRequests.Add(item);
target.Node.Value = SdkValueBoundary.FromClr(detached.Snapshot.Value,
target.Metadata.ValueKind == DataValueKind.Array && target.Metadata.ArrayElementKind == DataValueKind.UInt8);
target.Node.StatusCode = detached.Snapshot.StatusCode;
@@ -4851,7 +4857,48 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
DataValueKind.Timestamp => value is DateTime or DateTimeOffset, _ => false
};
- private readonly Dictionary Guard)> _projectedVariables = new();
+ private readonly ProjectedVariableTable _projectedVariables = new();
+
+ ///
+ /// #994 (U-12): the projected-variable map plus a per-parent child count kept in step on every write, so "does this node
+ /// still have projected children" is one lookup — the eviction loop and the page-sink remove used to answer it with a
+ /// full Values.Any(child => child.Parent == id) scan per candidate (O(N²) per reservation at the node cap).
+ /// Writers hold Lock (as for the plain dictionary it replaces).
+ ///
+ private sealed class ProjectedVariableTable
+ {
+ private readonly Dictionary Guard)> _entries = new();
+ private readonly Dictionary _children = new();
+ internal int Count => _entries.Count;
+ internal Dictionary Guard)>.KeyCollection Keys => _entries.Keys;
+ internal bool HasChildren(NodeId parent) => _children.ContainsKey(parent);
+ internal bool TryGetValue(NodeId id, out (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func Guard) entry) =>
+ _entries.TryGetValue(id, out entry);
+ internal (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func Guard) this[NodeId id]
+ {
+ get => _entries[id];
+ set
+ {
+ if (_entries.TryGetValue(id, out var previous)) Release(previous.Parent);
+ _entries[id] = value; Retain(value.Parent);
+ }
+ }
+ internal void Add(NodeId id, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func Guard) entry)
+ { _entries.Add(id, entry); Retain(entry.Parent); }
+ internal bool Remove(NodeId id) => Remove(id, out _);
+ internal bool Remove(NodeId id, out (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func Guard) entry)
+ {
+ if (!_entries.Remove(id, out entry)) return false;
+ Release(entry.Parent); return true;
+ }
+ internal void Clear() { _entries.Clear(); _children.Clear(); }
+ private void Retain(NodeId parent) { _children.TryGetValue(parent, out var count); _children[parent] = count + 1; }
+ private void Release(NodeId parent)
+ {
+ if (!_children.TryGetValue(parent, out var count)) return;
+ if (count <= 1) _children.Remove(parent); else _children[parent] = count - 1;
+ }
+ }
bool IProjectedNamespacePageSink.TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected,
ProjectedVariableDefinition replacement, Func commit)
@@ -5048,7 +5095,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
_projectedNodeCharges[anchorId] = anchorCharge + charge; _projectedNodeBytes += charge; charged = true;
if (!installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false;
CommitProjectedDefinition(anchorId, installed);
- accepted = true; return true;
+ accepted = true;
+ // #994 (U-11): the folder this NodeId named is gone (swapped for the leaf variable): unwire it and tombstone its
+ // monitored node so no item keeps pointing at the dead folder. Only once the swap is accepted — a refused swap
+ // restores the folder untouched.
+ OnProjectedFolderRemoving(anchorId);
+ TombstoneMonitoredNode(anchorId, UtcNow);
+ return true;
}
finally
{
@@ -5070,7 +5123,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
if (_disposing || _projectedRootLeaves.ContainsKey(nodeId) || !_projectedDefinitions.TryGetValue(nodeId, out var current) || !ReferenceEquals(current, expected) ||
IsPinnedEventFolder(nodeId) || // A3 N7: a folder holding an admitted event item is not retired
- _projectedVariables.Values.Any(child => child.Parent == nodeId) || !_projectedVariables.Remove(nodeId, out var entry)) return false;
+ _projectedVariables.HasChildren(nodeId) || !_projectedVariables.Remove(nodeId, out var entry)) return false;
OnProjectedFolderRemoving(nodeId);
_projectedDefinitions.Remove(nodeId); RemoveProjectedSample(nodeId); RetireProjectedCharge(nodeId, current.Lifetime);
TombstoneMonitoredNode(nodeId, UtcNow);
@@ -6836,7 +6889,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
///
internal void TrackLiveMonitoredItem(NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem)
{
- if (OwnsNamespace(handle.NodeId)) _liveItems[monitoredItem] = new LiveItem(handle);
+ if (OwnsNamespace(handle.NodeId)) LiveTrack(monitoredItem, new LiveItem(handle));
if (monitoredItem is ProjectedMonitoredItem projected) TrackProjectedHealth(projected);
}
@@ -6845,7 +6898,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
ServerSystemContext context, NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem)
{
if (monitoredItem is ProjectedMonitoredItem projected) { ForgetProjectedHealth(projected); projected.Retire(); }
- if (_liveItems.TryRemove(monitoredItem, out var tracked) && tracked.Suppressed) Interlocked.Decrement(ref _suppressedItems);
+ if (LiveUntrack(monitoredItem, out var tracked) && tracked!.Suppressed) Interlocked.Decrement(ref _suppressedItems);
base.OnMonitoredItemDeleted(context, handle, monitoredItem);
}
@@ -6931,7 +6984,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
if (item is ProjectedMonitoredItem projected) projected.Retire();
TellNodeRemoved(item, now);
- if (item is ISampledDataChangeMonitoredItem sampled) _liveItems.TryRemove(sampled, out _);
+ if (item is ISampledDataChangeMonitoredItem sampled) LiveUntrack(sampled, out _);
ReleaseComponentCacheReference(item);
}
}
@@ -6988,7 +7041,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var (item, tracked) in _liveItems)
{
if (!tracked.Suppressed || (nodeId is not null && tracked.Handle.NodeId != nodeId.Value)) continue;
- if (!_liveItems.TryRemove(item, out _)) continue;
+ if (!LiveUntrack(item, out _)) continue;
Interlocked.Decrement(ref _suppressedItems);
if (item is ProjectedMonitoredItem projected) projected.Retire();
TellNodeRemoved(item, now);
@@ -7151,6 +7204,49 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// for every create and delete including subscription teardown, so the map cannot outlive the items.
///
private readonly ConcurrentDictionary _liveItems = new();
+
+ // #994 (U-10): the projected members of _liveItems indexed by their node, kept in step by the three helpers below (the ONLY
+ // writers of _liveItems). Guarded by its own small gate, never held while calling out, so TryPublish (under Lock) and the
+ // SDK create/delete paths (not under Lock) can both use it without a lock-order edge.
+ private readonly object _projectedLiveGate = new();
+ private readonly Dictionary> _projectedLiveByNode = new();
+ private static readonly ProjectedMonitoredItem[] NoProjectedItems = [];
+
+ private void LiveTrack(ISampledDataChangeMonitoredItem item, LiveItem live)
+ {
+ _liveItems[item] = live;
+ if (item is not ProjectedMonitoredItem projected) return;
+ lock (_projectedLiveGate)
+ {
+ if (!_projectedLiveByNode.TryGetValue(projected.ProjectedNodeId, out var set))
+ _projectedLiveByNode.Add(projected.ProjectedNodeId, set = []);
+ set.Add(projected);
+ }
+ }
+
+ private bool LiveUntrack(ISampledDataChangeMonitoredItem item, out LiveItem? tracked)
+ {
+ if (!_liveItems.TryRemove(item, out tracked)) return false;
+ if (item is ProjectedMonitoredItem projected)
+ lock (_projectedLiveGate)
+ if (_projectedLiveByNode.TryGetValue(projected.ProjectedNodeId, out var set) && set.Remove(projected) && set.Count == 0)
+ _projectedLiveByNode.Remove(projected.ProjectedNodeId);
+ return true;
+ }
+
+ private void LiveClear()
+ {
+ _liveItems.Clear();
+ lock (_projectedLiveGate) _projectedLiveByNode.Clear();
+ }
+
+ private ProjectedMonitoredItem[] ProjectedLiveItemsFor(NodeId nodeId)
+ {
+ lock (_projectedLiveGate)
+ return _projectedLiveByNode.TryGetValue(nodeId, out var set) && set.Count != 0 ? [.. set] : NoProjectedItems;
+ }
+
+ internal int ProjectedLiveIndexCountForTests { get { lock (_projectedLiveGate) return _projectedLiveByNode.Sum(x => x.Value.Count); } }
private readonly object _projectedHealthGate = new();
private readonly LinkedList _projectedHealthItems = new();
private readonly Dictionary> _projectedHealthIndex = new();
@@ -8737,7 +8833,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
else
{
- _liveItems.TryRemove(item, out _); current.Suppressed = false;
+ LiveUntrack(item, out _); current.Suppressed = false;
Interlocked.Decrement(ref _suppressedItems); removed = true;
}
}
@@ -8808,7 +8904,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
: ResolveNodeState(MapKey(nodeId))) is { } liveNode
&& ReferenceEquals(liveNode, tracked.Handle.Node);
if (reattached) tracked.Handle.MonitoredNode?.Add(item);
- else _liveItems.TryRemove(item, out _);
+ else LiveUntrack(item, out _);
}
Interlocked.Decrement(ref _suppressedItems);
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs
index bfe7290fb..09475c11c 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs
@@ -140,6 +140,10 @@ internal sealed class ProjectedConditionRegistry
internal static readonly TimeSpan PositiveVerdictTtl = TimeSpan.FromSeconds(5);
private readonly object _verdictGate = new();
private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed, DateTimeOffset ValidUntil)> _verdicts = new();
+ /// #994 (U-13): condition → the identities holding a cached verdict for it, so a removal purges exactly its own
+ /// entries instead of scanning every cached verdict (up to 65,536) under the manager Lock.
+ private readonly Dictionary> _verdictIdentities = new();
+ internal int VerdictCountForTests { get { lock (_verdictGate) return _verdicts.Count; } }
public int Count => _byNode.Count;
public IEnumerable All => _byNode.Values;
@@ -163,7 +167,8 @@ internal sealed class ProjectedConditionRegistry
foreach (var key in condition.Placements.Select(FolderKey).Distinct())
if (ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0) ByFolderKey.Remove(key);
lock (_verdictGate)
- foreach (var stale in _verdicts.Keys.Where(k => k.Condition == condition.Alarm.NodeId).ToList()) _verdicts.Remove(stale);
+ if (_verdictIdentities.Remove(condition.Alarm.NodeId, out var identities))
+ foreach (var identity in identities) _verdicts.Remove((identity, condition.Alarm.NodeId));
}
public static (string, string) FolderKey(ImportedConditionPlacement p) => (p.MappingId, p.FolderLocalSubject);
@@ -192,8 +197,10 @@ internal sealed class ProjectedConditionRegistry
// only while THIS instance is still the live one (Remove drops it from _byInstance before purging under this gate),
// so a same-NodeId re-creation never inherits a verdict computed for the removed instance.
if (!_byInstance.ContainsKey(condition.Alarm)) return allowed;
- if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation
+ if (_verdicts.Count >= 65_536) { _verdicts.Clear(); _verdictIdentities.Clear(); } // bounded: a flood of identities only costs recomputation
_verdicts[key] = (generation, condition.PlacementVersion, allowed, validUntil);
+ if (!_verdictIdentities.TryGetValue(key.NodeId, out var identities)) _verdictIdentities.Add(key.NodeId, identities = []);
+ identities.Add(identity);
}
return allowed;
}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs
index 3f193be75..1c6fc637d 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs
@@ -190,10 +190,15 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
NotifyRetirements();
}
- public bool TryPublish(IReadOnlyList updates)
+ public bool TryPublish(IReadOnlyList updates) => Publish(updates, backpressure: false) == ProjectedPublishOutcome.Accepted;
+
+ ///
+ public ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList updates) => Publish(updates, backpressure: true);
+
+ private ProjectedPublishOutcome Publish(IReadOnlyList updates, bool backpressure)
{
ArgumentNullException.ThrowIfNull(updates);
- if (updates.Count == 0 || updates.Count > _maximumRoutes) { Invalidate(updates); return false; }
+ if (updates.Count == 0 || updates.Count > _maximumRoutes) { Invalidate(updates); return ProjectedPublishOutcome.Refused; }
var captured = updates.ToArray();
var bindings = new Binding[captured.Length];
long charge = 256;
@@ -209,6 +214,7 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
charge = checked(charge + 512 + OwnedDataSample.Estimate(update.Snapshot.Value));
}
var admitted = false;
+ var full = false;
lock (_sync)
{
if (!_disposed && charge <= _maximumBytes - _pendingBytes)
@@ -219,7 +225,10 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
{ admitted = false; break; }
if (admitted) _pendingBytes += charge;
}
+ else full = !_disposed && charge <= _maximumBytes;
}
+ // #994 (R-10): a full pending budget is local backpressure, not invalid evidence — the proof and the route stay.
+ if (!admitted && full && backpressure) return ProjectedPublishOutcome.CapacityExhausted;
if (!admitted) return Refused();
}
catch (Exception error) when (error is ArgumentException or OverflowException) { return Refused(); }
@@ -239,17 +248,17 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
batch.QueueSequence = checked(++_nextQueueSequence);
_pending.Add(batch);
}
- if (!batch.IsValid || Host() is not { } host) { batch.AbortQueued(); return false; }
+ if (!batch.IsValid || Host() is not { } host) { batch.AbortQueued(); return ProjectedPublishOutcome.Refused; }
NotifyValues(host);
- return true;
+ return ProjectedPublishOutcome.Accepted;
}
catch (Exception)
{
if (batch is not null) batch.AbortQueued();
else { lock (_sync) _pendingBytes -= charge; Invalidate(captured); }
- return false;
+ return ProjectedPublishOutcome.Refused;
}
- bool Refused() { Invalidate(captured); return false; }
+ ProjectedPublishOutcome Refused() { Invalidate(captured); return ProjectedPublishOutcome.Refused; }
void Complete(ProjectedPublicationBatch completed)
{ lock (_sync) { _pending.Remove(completed); _sdkPending.Remove(completed); _pendingBytes -= charge; } }
}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs
index 6d7dcd229..21ad4b767 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs
@@ -704,8 +704,12 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor
{
public ServingIdentity Serving { get; } = serving;
}
- private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport
+ private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport,
+ IDataSubscriptionCommandLimits
{
+ /// #994 (R-2): the peer's batch limit, within the connection row's batch and monitored-item caps.
+ public int MaxCommandItems => Math.Min(inner is IDataSubscriptionCommandLimits { MaxCommandItems: > 0 } limits ? limits.MaxCommandItems : owner._batch,
+ Math.Min(owner._batch, owner._monitored));
public bool SupportsFreshnessChallenges => inner is IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true };
public int FreshnessMaxItems => inner is IDataSubscriptionFreshnessSupport support && support.SupportsFreshnessChallenges
? Math.Min(support.FreshnessMaxItems, Math.Min(owner._batch, owner._monitored)) : 0;
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs
index f475e05eb..d08649062 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs
@@ -5,8 +5,10 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// One caller-bound subscription with bounded commands and one ordered delivery mode.
-internal sealed partial class DataSubscriptionSession : IDataSubscriptionTransport
+internal sealed partial class DataSubscriptionSession : IDataSubscriptionTransport, IDataSubscriptionCommandLimits
{
+ /// #994 (R-2): one command may carry up to the origin's batch limit.
+ public int MaxCommandItems => _services.SubscriptionLimits.MaxBatchItems;
private readonly LocalDataServices _services;
private readonly DataAuthenticatedContext _context;
private readonly DataTarget _target;
@@ -206,7 +208,12 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
{ SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
_outbound = Channel.CreateBounded(new BoundedChannelOptions(limits.MaxPendingFrames)
{ SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.Wait });
- _scheduler = new DeliveryScheduler(limits.MaxPendingFrames * 16, limits.MaxPendingFrames * 16);
+ // #994 (R-2): the delivery index must hold every item (and every distinct source) the stream may admit. It was sized
+ // from the frame window alone (MaxPendingFrames × 16 = 1024 by default), so the 1025th item — inside the advertised
+ // MaxMonitoredItems — failed registration AFTER its acknowledgement and stopped the whole session.
+ var schedulerCapacity = checked(Math.Max(limits.MaxPendingFrames * 16, services.SubscriptionLimits.MaxMonitoredItems) +
+ limits.MaxPendingFrames * 16);
+ _scheduler = new DeliveryScheduler(schedulerCapacity, schedulerCapacity);
var preOpen = limits.PreOpenTimeout ?? TimeSpan.FromSeconds(10);
_preOpen = services.Clock.CreateTimer(static state => ((DataSubscriptionSession)state!).Stop(), this,
preOpen, Timeout.InfiniteTimeSpan);
@@ -343,9 +350,11 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
else
{
if (_handles is null || command.SubscriptionId != _subscriptionId || command.StreamEpoch != _epoch) { Stop(); break; }
- if (command is ModifySubscriptionItems && HasIncompleteSnapshot() ||
- command is ChallengeSubscriptionFreshness && HasOutstandingSnapshots())
- { _deferred.Enqueue(work); retained = true; Interlocked.CompareExchange(ref _barrier, 1, 0); continue; }
+ // #994 (R-23): decide AND arm under the gate the SnapshotEnd commit decides its release under. A check
+ // released before the CAS let that commit's ReleaseBarrier(1) find 0 and no-op, after which the CAS
+ // armed a barrier nothing would release: every later command deferred until its ack timeout.
+ if (TryArmSnapshotBarrier(command))
+ { AfterSnapshotBarrierCheckForTests?.Invoke(); _deferred.Enqueue(work); retained = true; continue; }
switch (command)
{
case AddSubscriptionItems add: await AddAsync(add.Items, add.CommandId, work.Started, add.AcknowledgementTimeout).ConfigureAwait(false); break;
@@ -399,6 +408,20 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
lock (_gate) return _snapshots.Count != 0;
}
+ internal Action? AfterSnapshotBarrierCheckForTests { get; set; }
+ internal Action? SnapshotEndReleasedForTests { get; set; }
+
+ private bool TryArmSnapshotBarrier(DataSubscriptionCommand command)
+ {
+ lock (_gate)
+ {
+ var defer = command is ModifySubscriptionItems && _interests.Any(group => !group.SnapshotComplete) ||
+ command is ChallengeSubscriptionFreshness && _snapshots.Count != 0;
+ if (defer) Interlocked.CompareExchange(ref _barrier, 1, 0);
+ return defer;
+ }
+ }
+
private void ReleaseBarrier(int expected)
{
if (Interlocked.CompareExchange(ref _barrier, 0, expected) != expected) return;
@@ -874,9 +897,13 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
await PumpSnapshotsAsync().ConfigureAwait(false);
await PumpConditionsAsync().ConfigureAwait(false);
BeforeDirtyTickForTests?.Invoke(_outbound.Reader.Count, Volatile.Read(ref _queuedValues), interests.Count);
+ // #994 (R-3): each group drains up to 256 of ITS OWN changes per tick, walking at most 4096 partition entries (unrelated
+ // traffic no longer eats the budget); a group still behind re-queues a tick instead of waiting 100 ms, and a group that
+ // fell off the bounded history catches up from per-source versions rather than resetting the stream.
+ var behind = false;
foreach (var group in interests)
{
- if (!group.Lease.TryReadChanges(32, out var changes))
+ if (!group.Lease.TryReadChanges(256, 4096, out var changes, out var more))
{
// #962: a modify's ack commit runs on the delivery side and can release a group this tick captured
// above (the replaced item's interest); its disposed lease then reads like a reset. That group is gone
@@ -887,7 +914,9 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
CloseWithReset("Source change history expired."); return;
}
foreach (var change in changes) MarkDirty(change.Ticket.Key);
+ behind |= more;
}
+ if (behind) QueueTick();
var availableValues = AvailableValueSlots();
if (availableValues > 0)
foreach (var scheduled in _scheduler.TakeSlice(Math.Min(32, availableValues)))
@@ -997,6 +1026,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
if (job.TemporaryInterest) FinishChallengeSnapshot(job);
QueueTick();
if (allComplete) ReleaseBarrier(1);
+ SnapshotEndReleasedForTests?.Invoke();
}, () =>
{
job.Snapshot.Dispose(); job.Admission.Dispose();
@@ -1080,15 +1110,18 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
if (snapshotHold is not null) lease = new CompositeLease(lease, snapshotHold);
}
catch { owned.Dispose(); snapshotHold?.Dispose(); _services.SubscriptionHub.Resources.Release(charge); return null; }
- bool Gate() => item.Ticket is { } ticket &&
+ bool Identity() => item.Ticket is { } ticket &&
(snapshotLease is null || snapshotLease.IsItemCurrent(ticket) && snapshotPermit?.IsValid == true) &&
Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && _handles!.IsCurrent(item.Handle) &&
- _services.SubscriptionHub.IsTicketCurrentNonBlocking(ticket) && item.View.CanPublish();
+ _services.SubscriptionHub.IsTicketCurrentNonBlocking(ticket);
+ bool Gate() => Identity() && item.View.CanPublish();
bool Commit()
{
+ // #994 (R-12): the frame was authorized by Gate() right before the transport write it now commits; under the session
+ // lock only the cheap identity fences are re-checked (the authorization walk no longer runs while holding _gate).
lock (_gate)
{
- if (!Gate() || !_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return false;
+ if (!Identity() || !_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return false;
if (!_services.SubscriptionHub.Resources.TryReserve(charge)) return false;
var next = new BudgetLease(_services.SubscriptionHub.Resources, charge);
item.Filter.Commit(owned); item.BaselineCharge?.Dispose(); item.BaselineCharge = next;
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs
index e4da93646..8eafb88d9 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs
@@ -339,23 +339,35 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false);
if (!admitted) throw new InvalidOperationException("Unary capacity exhausted.");
if (!ProbeAllowed()) throw new InvalidOperationException("Data endpoint discovery is backing off.");
+ // #994 (R-8): only an endpoint that could not be SELECTED arms the connection-wide discovery backoff. A caller's
+ // cancel/deadline is the caller's cancellation (never an endpoint failure), and a per-call fault after a successful
+ // selection (a bad node id, a refused item, an oversized answer) fails this call alone — it used to refuse every
+ // other subscribe/write/read on the connection for the backoff window.
+ var selectedAny = false;
foreach (var endpoint in _endpoints)
{
Check();
+ Selected selected;
+ try { selected = await SelectAsync(endpoint, start, budget, false, ct).ConfigureAwait(false); }
+ catch (Exception ex) when (ct.IsCancellationRequested && ex is RpcException or OperationCanceledException)
+ { throw new OperationCanceledException("Data request cancelled by the caller.", ex, ct); }
+ catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
+ { failure = ex; RecordFailure(ex); continue; }
+ ProbeSucceeded(); selectedAny = true;
try
{
- var selected = await SelectAsync(endpoint, start, budget, false, ct).ConfigureAwait(false);
- ProbeSucceeded();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token);
var remaining = budget with { Timeout = Remaining(start, budget) };
var result = await call(selected, remaining, Options(selected, start, budget, linked.Token)).ConfigureAwait(false);
try { linked.Token.ThrowIfCancellationRequested(); return result; }
catch { if (result is IEnumerable reads) foreach (var item in reads) item.Dispose(); throw; }
}
+ catch (Exception ex) when (ct.IsCancellationRequested && ex is RpcException or OperationCanceledException)
+ { throw new OperationCanceledException("Data request cancelled by the caller.", ex, ct); }
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; RecordFailure(ex); }
}
- ProbeFailed();
+ if (!selectedAny) ProbeFailed();
throw new InvalidOperationException("No ready authenticated data endpoint.", failure);
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
@@ -686,9 +698,12 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
AsyncDuplexStreamingCall call, Selected selected,
CancellationTokenSource lifetime, bool compactNegotiated, int maxBytes, int maxItems, int maxPendingCommands,
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func claimEpoch, Action? observePending,
- Func? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance, IDataSubscriptionFreshnessSupport
+ Func? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance, IDataSubscriptionFreshnessSupport,
+ IDataSubscriptionCommandLimits
{
public ServingIdentity Serving { get; } = selected.Capabilities.Serving;
+ /// #994 (R-2): the origin's advertised batch limit, within this stream's own item cap.
+ public int MaxCommandItems => Math.Min(selected.Capabilities.Limits.MaxBatchItems, maxItems);
public bool SupportsFreshnessChallenges => selected.Capabilities.SubscriptionFreshnessChallenges && selected.Capabilities.SubscriptionAgeReadiness;
public int FreshnessMaxItems => selected.Capabilities.Limits.MaxBatchItems;
private readonly Dictionary _freshnessStarts = new(StringComparer.Ordinal);
@@ -878,10 +893,13 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
}
var requested = pending.ClientIds ?? pending.Removed!.Select(_ => (string?)null).ToArray();
if (ack.Items.Count != requested.Length) throw new InvalidOperationException("Unexpected acknowledgement count.");
- var next = new Dictionary(_handles);
- var nextClients = new Dictionary(_clientHandles, StringComparer.Ordinal);
- var nextUsed = new HashSet(_usedHandles);
- var nextVersions = new Dictionary(_versions);
+ // #994 (R-13): the tables are mutated IN PLACE. Only this reader touches them, and any throw below ends the
+ // stream (the enumerator's finally disposes it), so the copy-then-commit this replaced bought nothing but
+ // four whole-table copies per acknowledgement (O(N²) across an N-item open).
+ var next = _handles;
+ var nextClients = _clientHandles;
+ var nextUsed = _usedHandles;
+ var nextVersions = _versions;
for (var i = 0; i < ack.Items.Count; i++)
{
var item = ack.Items[i];
@@ -931,7 +949,6 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
if (!_pending.Remove(ack.CommandId)) throw new InvalidOperationException("Acknowledgement expired.");
_pendingBytes -= pending.Bytes; commandBudget.Release(pending.Bytes);
pending.Timer.Cancel(); pending.Timer.Dispose();
- _handles = next; _clientHandles = nextClients; _usedHandles = nextUsed; _versions = nextVersions;
Volatile.Write(ref DiagnosticRegistrationCount, next.Count);
}
}
@@ -940,15 +957,17 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
throw new InvalidOperationException("Condition frame for an unknown handle.");
if (frame is DataSubscriptionValues values)
{
- var nextVersions = new Dictionary(_versions);
- var seen = new HashSet();
+ // #994 (R-13): validate against the live table, then apply in place (a per-frame copy of the versions
+ // table was ~280 KB of LOH garbage per frame at 10k handles). A throw ends the stream either way.
+ HashSet? seen = values.Items.Count > 1 ? new HashSet(values.Items.Count) : null;
foreach (var item in values.Items)
{
- if (!seen.Add(item.Handle.Handle) || nextVersions.TryGetValue(item.Handle.Handle, out var previous) && item.Sample.Version < previous)
+ if (seen is not null && !seen.Add(item.Handle.Handle) ||
+ _versions.TryGetValue(item.Handle.Handle, out var previous) && item.Sample.Version < previous)
throw new InvalidOperationException("Duplicate handle or sample version regression.");
- nextVersions[item.Handle.Handle] = item.Sample.Version;
}
- Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); _versions = nextVersions;
+ Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested();
+ foreach (var item in values.Items) _versions[item.Handle.Handle] = item.Sample.Version;
if (SupportsFreshnessChallenges)
{
var bounded = new List(values.Items.Count);
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs
index 7107aea54..88b655d15 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs
@@ -45,8 +45,18 @@ public interface IProjectedValuePublisher
bool TryBind(ProjectedValueRoute route);
bool TryPublish(IReadOnlyList updates);
void Retire(ProjectedValueRoute route);
+ ///
+ /// #994 (R-10): like , but a refusal for lack of local capacity (pending bytes) answers
+ /// WITHOUT invalidating the proof or retiring the route — the
+ /// evidence is fine, only the sink is momentarily full, so the caller backs off and retries.
+ ///
+ ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList updates) =>
+ TryPublish(updates) ? ProjectedPublishOutcome.Accepted : ProjectedPublishOutcome.Refused;
}
+/// #994 (R-10): the outcome of a projected publication.
+public enum ProjectedPublishOutcome { Accepted, Refused, CapacityExhausted }
+
/// A driver facade over a configured, scoped data connection.
public sealed class GrpcDataDriverAdapter : IDriver, IBatchSubscribable, IWriteOutcomeCapability
{
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs
index 0fe264565..742cb6f15 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs
@@ -183,16 +183,37 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
var serving = catalog.Serving;
var consistency = string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
? DataConsistency.Primary : DataConsistency.ReadyReplica;
+ // #994 (R-12): the publish verdict is re-evaluated on every delivered frame (several times). The expensive half — the
+ // catalog resolve, export-rule ancestry walk and ACL evaluation — is memoised against the exact catalog instance and
+ // authority generation it was computed for, for at most PublishVerdictTtl; the cheap readiness/serving identity checks
+ // run every time. Any catalog swap or authority publish (ACL, key revocation) misses the memo; a credential's expiry is
+ // separately enforced by the session's expiry timer.
+ PublishVerdict? memo = null;
authorized = new(node.Metadata.View, source, serving, node.Metadata, context.PrincipalId,
catalog.SubscriptionExportScope(context.PrincipalId, node), target, consistency, () =>
{
var current = _catalog();
- return current is not null && current.Serving == serving && current.TryResolve(view, out var now) &&
- now.Source == source && Allowed(current, context, now, DataOperations.Subscribe);
+ if (current is null || current.Serving != serving || !Ready(current)) return false;
+ var epoch = _policy.AuthorityEpoch;
+ var now = Clock.GetTimestamp();
+ var cached = Volatile.Read(ref memo);
+ if (cached is not null && ReferenceEquals(cached.Catalog, current) && cached.AuthorityEpoch == epoch &&
+ Clock.GetElapsedTime(cached.At, now) < PublishVerdictTtl)
+ return cached.Allowed;
+ Interlocked.Increment(ref _publishVerdictEvaluations);
+ var allowed = current.TryResolve(view, out var resolved) && resolved.Source == source &&
+ Allowed(current, context, resolved, DataOperations.Subscribe);
+ Volatile.Write(ref memo, new PublishVerdict(current, epoch, now, allowed));
+ return allowed;
});
return DataItemStatus.Good;
}
+ /// #994 (R-12): how long a memoised per-item publish verdict may be reused for the same catalog + authority.
+ internal static readonly TimeSpan PublishVerdictTtl = TimeSpan.FromSeconds(1);
+ private sealed record PublishVerdict(LocalExportCatalog Catalog, long AuthorityEpoch, long At, bool Allowed);
+ private long _publishVerdictEvaluations;
+ internal long PublishVerdictEvaluationsForTests => Interlocked.Read(ref _publishVerdictEvaluations);
internal PartitionedSampleHub SubscriptionHub => _hub;
internal DataLimits SubscriptionLimits => _capabilities.Limits;
internal int SubscriptionItemLimit(DataAuthenticatedContext context)
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs
index d732203e5..a39b17e8a 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs
@@ -17,6 +17,9 @@ internal sealed class OriginHistorySession
private readonly TimeProvider _clock;
private readonly OriginHistorySessions _owner;
private CancellationTokenRegistration _closed;
+ // #994 (R-22): set under _gate by Clear. A request that still holds this (now orphaned) session must not store a chunk in
+ // it — nothing would ever sweep it, and its bytes would stay charged to the principal for the life of the process.
+ private bool _cleared;
internal OriginHistorySession(OriginHistorySessions owner, string principal, string channelId, int capacity, TimeProvider clock)
{
@@ -84,7 +87,7 @@ internal sealed class OriginHistorySession
lock (_gate)
{
Sweep(_clock.GetTimestamp());
- if (_chunks.Count >= Capacity)
+ if (_cleared || _chunks.Count >= Capacity)
{
_owner.ReleaseBytes(Principal, chunk.Bytes);
return null;
@@ -126,7 +129,7 @@ internal sealed class OriginHistorySession
_closed.Unregister();
Cursors.Clear();
Chunk[] dropped;
- lock (_gate) { dropped = _chunks.Values.ToArray(); _chunks.Clear(); }
+ lock (_gate) { _cleared = true; dropped = _chunks.Values.ToArray(); _chunks.Clear(); }
foreach (var chunk in dropped) Drop(chunk);
}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs
index 8318b3564..23cb3506a 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs
@@ -294,6 +294,7 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
var controls = new Dictionary();
var quietControls = new Dictionary();
var owners = new Dictionary();
+ var quietVersions = new Dictionary();
long snapshotCharge = 0, interestCharge = 0;
try
{
@@ -304,7 +305,7 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
long watermark = 0, epoch = 0, control = 0, quietControl = 0;
var ok = !cancellationToken.IsCancellationRequested && routing == RoutingEpoch && partitions[group.Key].RoutingEpoch == routing && partitions[group.Key].Control.TryCapture(out control) &&
partitions[group.Key].Control.Quiet.TryCapture(out quietControl) &&
- partitions[group.Key].CaptureAndRegister(group.ToArray(), items, captured, out watermark,
+ partitions[group.Key].CaptureAndRegister(group.ToArray(), items, captured, quietVersions, out watermark,
out epoch, ref snapshotCharge, ref interestCharge, Math.Min(budget.MaxBytes, _limits.MaxSnapshotBytes), admission);
foreach (var pair in captured) owners.Add(pair.Key, (partitions[group.Key], pair.Value));
if (!ok || !partitions[group.Key].Control.Matches(control) || !partitions[group.Key].Control.Quiet.Matches(quietControl)) return false;
@@ -316,7 +317,7 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
snapshot = new SnapshotLease(this, items, watermarks, epochs, controls, partitions, routing, snapshotCharge, tickets.Count,
budget.Timeout < _limits.MaxSnapshotLifetime ? budget.Timeout : _limits.MaxSnapshotLifetime, cancellationToken);
snapshotCharge = 0; items = null!; _snapshots.TryAdd(snapshot, 0);
- interest = new SourceInterestLease(this, owners, watermarks, epochs, quietControls, routing, interestCharge, cancellationToken);
+ interest = new SourceInterestLease(this, owners, watermarks, epochs, quietControls, quietVersions, routing, interestCharge, cancellationToken);
interestCharge = 0; owners = null!; _interests.TryAdd(interest, 0);
if (!snapshot.IsReset && !interest.IsReset) return true;
snapshot.Dispose(); ForgetSnapshot(snapshot); interest.Dispose(); snapshot = null; interest = null; return false;
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs
index 482f0f26a..ef836c82b 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs
@@ -550,13 +550,18 @@ public sealed partial class ProjectedConditionAccess
// however it ends — an abandoned fetch must not run on to its 10 s budget against a released lease.
using var fetches = CancellationTokenSource.CreateLinkedTokenSource(token);
var context = new StreamContext(subscription, subscriptionId, epoch, token, fetches.Token);
+ // #994 (R-24): the frame read can be left pending across loop iterations; the teardown cancels it and observes it
+ // BEFORE disposing the enumerator (an async iterator disposed mid-MoveNextAsync throws NotSupportedException, which
+ // replaced the stream's real failure in the "stream ended" log and left `next` to fault unobserved).
+ using var frameStop = CancellationTokenSource.CreateLinkedTokenSource(token);
+ IAsyncEnumerator? frames = null;
+ Task? next = null;
try
{
await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false,
TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false);
using var barrierTimer = _owner._clock.CreateTimer(_ => timeout.TrySetResult(), null, snapshotTimeout, Timeout.InfiniteTimeSpan);
- await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token);
- Task? next = null;
+ frames = subscription.ReadAllAsync(frameStop.Token).GetAsyncEnumerator(frameStop.Token);
while (true)
{
if (!barrierPassed && timeout.Task.IsCompleted)
@@ -626,6 +631,7 @@ public sealed partial class ProjectedConditionAccess
}
finally
{
+ await ProjectedStreamTeardown.StopAsync(frameStop, next, frames).ConfigureAwait(false);
retryTimer?.Dispose();
fetches.Cancel();
// #933 review r1 S2: the hold clock pauses while no stream is past its barrier.
@@ -1226,3 +1232,17 @@ public sealed partial class ProjectedConditionAccess
}
}
}
+
+///
+/// #994 (R-24): ends a frame loop that may have a MoveNextAsync still in flight — cancel it, observe it, then dispose
+/// the enumerator. Never throws: the loop's own failure (if any) is the one the caller reports.
+///
+internal static class ProjectedStreamTeardown
+{
+ internal static async Task StopAsync(CancellationTokenSource stop, Task? pending, IAsyncEnumerator? enumerator)
+ {
+ try { await stop.CancelAsync().ConfigureAwait(false); } catch (Exception) { }
+ if (pending is not null) { try { await pending.ConfigureAwait(false); } catch (Exception) { } }
+ if (enumerator is not null) { try { await enumerator.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } }
+ }
+}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs
index 12375c8ee..7e83e18ec 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs
@@ -1248,21 +1248,55 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
private sealed record RenewalEvent : Event;
private sealed record RenewedEvent(Demand Demand, Demand.Binding Expected, bool Success) : Event;
private sealed record EndEvent : Event;
+ /// #994 (R-2): the command pacer has a slot again; flush the queued adds/removes/challenges.
+ private sealed record FlushEvent : Event;
private sealed class Registration(Demand demand, string id)
{
internal readonly Demand Demand = demand; internal readonly string Id = id;
internal DataItemHandle? Handle; internal bool Removed, Rebinding, Recovery, AwaitingCurrent, NeedsChallenge, HasBaseline, Renewal;
internal IDataAuthorizationLease? RenewalPredecessor;
+ // #994 (R-13): the source this registration last published through, for the binding it was resolved under — a
+ // sample re-resolves (global lock, key allocation, read-source sweep) only when the binding moved or the source
+ // was retired (an invalidated source answers IsValid = false).
+ internal SourceState? CachedSource; internal Demand.Binding? CachedBinding;
}
private readonly ProjectedDataAccess _owner;
private CohortKey _key;
private readonly string _connectionId;
+ // #994 (R-7): ONE unbounded event channel. Control events (add/remove/refresh/renewal/flush) are bounded by the demand
+ // set itself (one add and one remove per demand, a refresh deduplicated per demand, timer ticks deduplicated by flag), so
+ // enqueueing one can never fail — a failed Remove used to Stop() the whole cohort and dispose every sibling demand.
+ // Value frames keep their backpressure through _frameSlots (and the _frameBytes budget), so a slow consumer still
+ // stalls the pump rather than growing memory.
private readonly Channel _events;
+ private readonly SemaphoreSlim _frameSlots;
private readonly CancellationTokenSource _stop = new();
private readonly Dictionary _registrations = new();
private readonly Dictionary _byId = new(StringComparer.Ordinal);
private readonly Dictionary _byHandle = new();
- private readonly Dictionary _removing = new(StringComparer.Ordinal);
+ private readonly Dictionary> _removing = new(StringComparer.Ordinal);
+ // #994 (R-2): a per-cohort command pacer. The origin admits MaxCommandsPerSecond (default 128) commands per principal
+ // and STOPS the session past it; batching keeps a whole open to a handful of commands, and the pacer bounds a churn
+ // of single adds/removes (each lets the queue grow, so the next send carries more items). Kept across attempts.
+ internal const int CommandBurst = 32;
+ internal const double CommandsPerSecond = 32;
+ ///
+ /// The most commands this cohort leaves un-acknowledged at once. The origin reserves its session's MaxPendingBytes
+ /// from the node-wide hub budget for every queued command (64 MiB / 1 MiB by default, shared by every session), so
+ /// a cohort must not flood it — a refused reservation fails the command and the whole attempt.
+ ///
+ internal const int MaxOutstandingCommands = 4;
+ /// Items per command when the stream does not advertise its peer's batch limit.
+ internal const int DefaultCommandItems = 64;
+ private double _commandTokens;
+ private long _commandTokenStamp;
+ private int _flushQueued;
+ // #994 (R-10): a publication the local sink refused for capacity is retried after a short wait (backpressure on this
+ // loop, so the pump and the origin back up) instead of invalidating healthy evidence; only after the bound does it
+ // fall back to the fail-closed invalidation (which re-snapshots). Both fields belong to the attempt loop's thread.
+ internal const int CapacityRetries = 200;
+ internal static readonly TimeSpan CapacityRetryDelay = TimeSpan.FromMilliseconds(10);
+ private bool _capacityRetryAllowed, _capacityRefused;
// Guarded by the owner's lock; at most one queued or active refresh per demand.
private readonly HashSet _refreshRequests = [];
private string _id = string.Empty;
@@ -1276,11 +1310,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
internal Cohort(ProjectedDataAccess owner, CohortKey key, string connectionId)
{
_owner = owner; _key = key; _connectionId = connectionId;
- _events = Channel.CreateBounded(new BoundedChannelOptions(Math.Clamp(owner._limits.MaxDemands * 2, 4, 128))
- { SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
+ _events = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true });
+ var frames = Math.Clamp(owner._limits.MaxDemands * 2, 4, 128);
+ _frameSlots = new SemaphoreSlim(frames, frames);
+ _commandTokens = CommandBurst; _commandTokenStamp = owner.Clock.GetTimestamp();
}
internal bool Add(Demand demand) => _events.Writer.TryWrite(new AddEvent(demand));
- internal void Remove(Demand demand) { if (!_events.Writer.TryWrite(new RemoveEvent(demand))) Stop(); }
+ // #994 (R-7): never tears the cohort down. The unbounded channel only refuses once completed (it never is); a disposed
+ // demand that is somehow not dequeued is reconciled by the next attempt's ReleaseDemand pass.
+ internal void Remove(Demand demand) => _events.Writer.TryWrite(new RemoveEvent(demand));
internal void Start() { if (Interlocked.Exchange(ref _started, 1) == 0) _ = Task.Run(RunAsync); }
internal void Stop() { if (Interlocked.Exchange(ref _closing, 1) == 0) _ = _stop.CancelAsync(); }
internal bool Refresh(Demand demand)
@@ -1305,12 +1343,71 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
checked(x.Sample.Value.EstimatedRetainedBytes + 2L * (x.FreshnessChallengeId?.Length ?? 0)))) : 512L;
if (bytes > _owner._limits.MaxUnaryBytes || Interlocked.Add(ref _frameBytes, bytes) > _owner._limits.MaxUnaryBytes)
{ Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; }
- try { await _events.Writer.WriteAsync(new FrameEvent(frame, bytes, receivedTimestamp), attemptStop).ConfigureAwait(false); }
+ // #994 (R-7): frames wait for a slot; control events never do (they share the channel, not the bound).
+ try { await _frameSlots.WaitAsync(attemptStop).ConfigureAwait(false); }
catch { Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); throw; }
+ if (!_events.Writer.TryWrite(new FrameEvent(frame, bytes, receivedTimestamp)))
+ { _frameSlots.Release(); Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; }
}
}
catch (Exception) { }
- finally { try { await _events.Writer.WriteAsync(new EndEvent(), attemptStop).ConfigureAwait(false); } catch (OperationCanceledException) { } }
+ finally { _events.Writer.TryWrite(new EndEvent()); }
+ }
+ /// #994 (R-2): the hard ceiling of items per command — the origin acquires each item's demand inside the
+ /// command's acknowledgement deadline, so a command must stay small enough to be answered in time.
+ internal const int MaxCommandItemsCap = 256;
+ internal static int CommandItemsFor(IDataSubscription stream, int maxDemands)
+ {
+ var advertised = stream is IDataSubscriptionCommandLimits { MaxCommandItems: > 0 } limits ? limits.MaxCommandItems : DefaultCommandItems;
+ return Math.Max(1, Math.Min(Math.Min(advertised, MaxCommandItemsCap), Math.Max(1, maxDemands)));
+ }
+ ///
+ /// #994 (R-2): how many queued registrations fit one add command: at most , and their
+ /// estimated command bytes and snapshot bytes (each answered item is one snapshot value, which the attempt holds
+ /// until the snapshot end and caps at ) stay within half of .
+ ///
+ private static int AddBatchSize(List queue, int commandItems, long maxBytes)
+ {
+ var budget = Math.Max(1, maxBytes / 2); long used = 0; var count = 0;
+ foreach (var registration in queue)
+ {
+ if (count >= commandItems) break;
+ var cost = ItemCostBytes(registration.Demand, registration.Id);
+ if (count > 0 && used + cost > budget) break;
+ used += cost; count++;
+ }
+ return Math.Max(1, count);
+ }
+ private static long ItemCostBytes(Demand demand, string clientItemId)
+ {
+ var view = demand.OriginView;
+ long wire = 512L + 2L * ((long)clientItemId.Length + (view.Subject?.Length ?? 0) + (view.MappingId?.Length ?? 0) +
+ (view.Address?.OriginClusterId?.Length ?? 0) + (view.Address?.NamespaceUri?.Length ?? 0) +
+ (view.Address?.IdentifierKind?.Length ?? 0) + (view.Address?.Identifier?.Length ?? 0));
+ var metadata = demand.Proof.OriginMetadata;
+ long value = metadata.ValueKind switch
+ {
+ DataValueKind.Array when metadata.ValueRank == 1 && metadata.Dimensions.Count == 1 && metadata.Dimensions[0] > 0 &&
+ metadata.ArrayElementKind is { } element && IsFixedSizeKind(element) => 512L + ProjectedFixedElementBytes * metadata.Dimensions[0],
+ var kind when IsFixedSizeKind(kind) => 1024L,
+ _ => ProjectedEnvelopeBytes,
+ };
+ return Math.Max(wire, value);
+ }
+ private bool TryTakeCommandToken()
+ {
+ var now = _owner.Clock.GetTimestamp();
+ var elapsed = Math.Max(0, _owner.Clock.GetElapsedTime(_commandTokenStamp, now).TotalSeconds);
+ _commandTokenStamp = now;
+ _commandTokens = Math.Min(CommandBurst, _commandTokens + elapsed * CommandsPerSecond);
+ if (_commandTokens < 1) return false;
+ _commandTokens -= 1; return true;
+ }
+ private void ArmFlush(ITimer? timer)
+ {
+ if (timer is null) return;
+ var wait = TimeSpan.FromSeconds(Math.Max(0, 1 - _commandTokens) / CommandsPerSecond) + TimeSpan.FromMilliseconds(1);
+ try { timer.Change(wait, Timeout.InfiniteTimeSpan); } catch (ObjectDisposedException) { }
}
private DataSubscriptionItem Item(Registration registration) => new(registration.Id, registration.Demand.OriginView,
new DataSubscriptionSettings(_key.Interval, _key.Interval, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataChangeTrigger.StatusValueTimestamp, null));
@@ -1523,7 +1620,13 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
var demandSources = new Dictionary();
var renewals = new Dictionary();
var renewalQueued = 0;
- var pendingCommands = new Dictionary();
+ var pendingCommands = new Dictionary>(StringComparer.Ordinal);
+ // #994 (R-2): registrations waiting for an add (open) command, and handles waiting for a remove command. Both are
+ // flushed in batches by FlushAsync — never one command per item.
+ var addQueue = new List();
+ var removeQueue = new List();
+ ITimer? flushTimer = null;
+ var commandItems = DefaultCommandItems;
var snapshotQueue = new Queue>();
HashSet? snapshotOwners = null;
void EnqueueSnapshot(HashSet owners)
@@ -1542,8 +1645,13 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
AttemptProof EvidenceFor(SourceState source, ProjectedNodeProof proof)
{
if (!evidence.TryGetValue(source, out var witnesses)) evidence[source] = witnesses = [];
- foreach (var expired in witnesses.Where(witness => !witness.LeaseValid).ToArray()) { expired.Close(); witnesses.Remove(expired); }
- var existing = witnesses.Find(witness => witness.Matches(proof));
+ AttemptProof? existing = null;
+ for (var i = witnesses.Count - 1; i >= 0; i--)
+ {
+ var witness = witnesses[i];
+ if (!witness.LeaseValid) { witness.Close(); witnesses.RemoveAt(i); }
+ else if (existing is null && witness.Matches(proof)) existing = witness;
+ }
if (existing is not null) return existing;
if (witnesses.Count >= 2) throw new InvalidDataException("Too many overlapping authority witnesses.");
var created = new AttemptProof(source, proof); witnesses.Add(created); return created;
@@ -1554,6 +1662,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
EvidenceFor(source, demand.Proof);
demandSources[demand] = source;
}
+ // #994 (R-2): a demand removed while its add was still queued (never sent) is dropped here, exactly as a removal
+ // acknowledgement would drop it.
+ void DropUnsent(Registration registration)
+ {
+ _registrations.Remove(registration.Demand); _byId.Remove(registration.Id);
+ UntrackSource(registration.Demand, registration.Renewal);
+ FinishRefresh(registration.Demand);
+ ReleaseDemand(registration.Demand);
+ }
void UntrackSource(Demand demand, bool preserve = false)
{
if (!demandSources.Remove(demand, out var source)) return;
@@ -1561,12 +1678,64 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (preserve) return;
if (evidence.Remove(source, out var witnesses)) foreach (var proof in witnesses) proof.Close();
}
+ async Task<(bool Accepted, bool Validated)> PublishPacedAsync(Registration registration, ProjectedValueUpdate update, long version,
+ CancellationToken token)
+ {
+ for (var attempt = 0; ; attempt++)
+ {
+ _capacityRetryAllowed = attempt < CapacityRetries; _capacityRefused = false;
+ var accepted = Publish(registration, update, version, out var validated);
+ if (!_capacityRefused) return (accepted, validated);
+ await Task.Delay(CapacityRetryDelay, token).ConfigureAwait(false);
+ }
+ }
+ // Commands not yet acknowledged AND snapshots not yet finished: the origin holds a snapshot admission per add and per
+ // challenge until its SnapshotEnd is delivered (MaxStreamsPerPrincipal per principal), and refusing one resets the stream.
+ int Outstanding() => pendingCommands.Count + _removing.Count + (challengeId is null ? 0 : 1) + snapshotQueue.Count + (inSnapshot ? 1 : 0);
+ bool TryTakeCommandSlot()
+ {
+ if (Outstanding() >= MaxOutstandingCommands) return false; // the next ack flushes again
+ if (TryTakeCommandToken()) return true;
+ ArmFlush(flushTimer);
+ return false;
+ }
+ async Task FlushAsync(CancellationToken token)
+ {
+ // Removes first: they free origin capacity the adds may need.
+ while (opened && removeQueue.Count > 0)
+ {
+ if (!TryTakeCommandSlot()) return;
+ var count = Math.Min(removeQueue.Count, commandItems);
+ var batch = removeQueue.GetRange(0, count); removeQueue.RemoveRange(0, count);
+ var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = batch;
+ await stream!.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5),
+ batch.Select(x => x.Handle!).ToArray()), token).ConfigureAwait(false);
+ }
+ while (addQueue.Count > 0)
+ {
+ if (!TryTakeCommandSlot()) return;
+ var count = AddBatchSize(addQueue, commandItems, _owner._limits.MaxUnaryBytes);
+ var batch = addQueue.GetRange(0, count); addQueue.RemoveRange(0, count);
+ var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, batch);
+ var items = batch.Select(Item).ToArray();
+ // The open's snapshot budget also sizes the origin's handle table for the stream: it must cover every
+ // demand this cohort may carry (it used to be 1, so a second item was refused LimitExceeded forever).
+ DataSubscriptionCommand command = !opened
+ ? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), items, false, TimeSpan.FromMinutes(1),
+ new(TimeSpan.FromSeconds(5), Math.Max(1, _owner._limits.MaxDemands), _owner._limits.MaxUnaryBytes))
+ : new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), items);
+ await stream!.SendAsync(command, token).ConfigureAwait(false); opened = true;
+ }
+ await ChallengeAsync(token).ConfigureAwait(false);
+ }
async Task ChallengeAsync(CancellationToken token)
{
if (challengeId is not null || stream is not IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true } support) return;
- var chosen = _registrations.Values.Where(x => x.NeedsChallenge && !x.Removed && x.Demand.IsValid && x.Handle is not null)
- .Take(Math.Min(128, support.FreshnessMaxItems)).ToArray();
+ var limit = Math.Min(commandItems, support.FreshnessMaxItems);
+ var chosen = _registrations.Values.Where(x => x.NeedsChallenge && !x.Removed && x.Handle is not null && x.Demand.IsValid)
+ .Take(Math.Max(1, limit)).ToArray();
if (chosen.Length == 0) return;
+ if (!TryTakeCommandSlot()) return;
foreach (var item in chosen) item.NeedsChallenge = false;
challengeId = "freshness-" + checked(++challengeSequence).ToString(System.Globalization.CultureInfo.InvariantCulture);
await stream.SendAsync(new ChallengeSubscriptionFreshness(_id, _epoch, challengeId, TimeSpan.FromSeconds(5),
@@ -1621,6 +1790,14 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{ Interlocked.Decrement(ref _owner._renewalTicksQueued); Interlocked.Exchange(ref renewalQueued, 0); }
}
}, null, renewalInterval, renewalInterval);
+ commandItems = CommandItemsFor(stream, _owner._limits.MaxDemands);
+ flushTimer = _owner.Clock.CreateTimer(static state =>
+ {
+ var cohort = (Cohort)state!;
+ if (Interlocked.Exchange(ref cohort._flushQueued, 1) == 0 && !cohort._events.Writer.TryWrite(new FlushEvent()))
+ Interlocked.Exchange(ref cohort._flushQueued, 0);
+ }, this, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
+ Interlocked.Exchange(ref _flushQueued, 0);
pump = PumpAsync(stream, route.Token);
foreach (var demand in initial)
{
@@ -1629,17 +1806,25 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
TrackSource(demand);
var registration = new Registration(demand, Guid.NewGuid().ToString("N")) { Recovery = _epoch > 1 };
_registrations[demand] = registration; _byId[registration.Id] = registration;
- var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, registration);
- DataSubscriptionCommand command = !opened
- ? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes))
- : new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)]);
- await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true;
+ addQueue.Add(registration);
}
// A temporarily unavailable proof must not leave an unopened stream parked
// forever. Retry the bounded attempt after backoff so renewal can make it usable.
- if (!opened) return;
- await foreach (var message in _events.Reader.ReadAllAsync(route.Token).ConfigureAwait(false))
+ if (addQueue.Count == 0) return;
+ await FlushAsync(route.Token).ConfigureAwait(false);
+ var sinceFlush = 0;
+ while (true)
{
+ // #994 (R-2): queued adds/removes go out whenever the event queue momentarily drains (or every 64 events
+ // under a sustained frame stream), so a burst of control events becomes a few batched commands.
+ if (!_events.Reader.TryRead(out var message))
+ {
+ sinceFlush = 0;
+ await FlushAsync(route.Token).ConfigureAwait(false);
+ message = await _events.Reader.ReadAsync(route.Token).ConfigureAwait(false);
+ }
+ else if (++sinceFlush >= 64) { sinceFlush = 0; await FlushAsync(route.Token).ConfigureAwait(false); }
+ if (message is FlushEvent) { Interlocked.Exchange(ref _flushQueued, 0); continue; }
if (message is AddEvent add)
{
lock (_owner._sync)
@@ -1656,11 +1841,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
Math.Min(TimeSpan.FromMilliseconds(250).Ticks, addedLease.UsableDuration.Ticks / 4)));
if (nextInterval < renewalInterval) { renewalInterval = nextInterval; renewalTimer.Change(nextInterval, nextInterval); }
}
- var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, registration);
- DataSubscriptionCommand command = !opened
- ? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes))
- : new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)]);
- await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true;
+ addQueue.Add(registration);
}
else if (message is RefreshEvent refresh)
{
@@ -1674,11 +1855,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
continue;
}
registration.Removed = true; registration.Rebinding = true;
- if (registration.Handle is { } handle)
- {
- var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
- await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
- }
+ if (registration.Handle is not null) removeQueue.Add(registration);
}
else if (message is RemoveEvent remove)
{
@@ -1689,11 +1866,9 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (!registration.Removed)
{
registration.Removed = true;
- if (registration.Handle is { } handle)
- {
- var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
- await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
- }
+ if (registration.Handle is not null) removeQueue.Add(registration);
+ // Never acknowledged yet: its add may still be queued here — drop it rather than open it.
+ else if (addQueue.Remove(registration)) { DropUnsent(registration); }
}
}
else ReleaseDemand(remove.Demand);
@@ -1704,7 +1879,6 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
Interlocked.Exchange(ref _freshnessQueued, 0);
if (_registrations.Values.Any(x => !x.Removed && !x.Demand.IsValid)) break;
foreach (var registration in _registrations.Values) registration.NeedsChallenge = true;
- await ChallengeAsync(route.Token).ConfigureAwait(false);
}
else if (message is RenewalEvent)
{
@@ -1746,11 +1920,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
renewed.Expected.NodePin.Dispose(); renewed.Expected.Pin.Dispose();
registration.Removed = true; registration.Rebinding = true; registration.Renewal = true;
registration.RenewalPredecessor = renewed.Expected.Proof.Lease;
- if (registration.Handle is { } handle)
- {
- var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
- await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
- }
+ if (registration.Handle is not null) removeQueue.Add(registration);
}
else if (message is EndEvent) break;
else if (message is FrameEvent delivered)
@@ -1769,49 +1939,53 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (ack.Items.Any(x => x.Status != DataItemStatus.Good || x.Handle is null ||
!_byHandle.TryGetValue(x.Handle, out var current) || current.Id != x.ClientItemId)) throw new InvalidDataException("Invalid freshness acknowledgement.");
EnqueueSnapshot(ack.Items.Select(x => _byHandle[x.Handle!]).ToHashSet());
- await ChallengeAsync(route.Token).ConfigureAwait(false);
}
- else if (_removing.Remove(ack.CommandId, out var removed))
+ else if (_removing.Remove(ack.CommandId, out var removedBatch))
{
- if (ack.Items.Count != 1 || ack.Items[0].Status != DataItemStatus.Good || ack.Items[0].Handle != removed.Handle || ack.Items[0].ClientItemId != removed.Id) throw new InvalidDataException("Invalid removal acknowledgement.");
- _registrations.Remove(removed.Demand); _byId.Remove(removed.Id);
- if (removed.Handle is { } removedHandle) _byHandle.Remove(removedHandle);
- UntrackSource(removed.Demand, removed.Renewal);
- if (removed.Rebinding && removed.Demand.IsValid)
+ if (ack.Items.Count != removedBatch.Count) throw new InvalidDataException("Invalid removal acknowledgement.");
+ for (var i = 0; i < removedBatch.Count; i++)
{
- var replacement = new Registration(removed.Demand, Guid.NewGuid().ToString("N"))
- { Recovery = true, Renewal = removed.Renewal, RenewalPredecessor = removed.RenewalPredecessor };
- _registrations[removed.Demand] = replacement; _byId[replacement.Id] = replacement;
- TrackSource(removed.Demand);
- var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, replacement);
- await stream.SendAsync(new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(replacement)]), route.Token).ConfigureAwait(false);
- continue;
+ var removed = removedBatch[i]; var answer = ack.Items[i];
+ if (answer.Status != DataItemStatus.Good || answer.Handle != removed.Handle || answer.ClientItemId != removed.Id) throw new InvalidDataException("Invalid removal acknowledgement.");
+ _registrations.Remove(removed.Demand); _byId.Remove(removed.Id);
+ if (removed.Handle is { } removedHandle) _byHandle.Remove(removedHandle);
+ UntrackSource(removed.Demand, removed.Renewal);
+ if (removed.Rebinding && removed.Demand.IsValid)
+ {
+ var replacement = new Registration(removed.Demand, Guid.NewGuid().ToString("N"))
+ { Recovery = true, Renewal = removed.Renewal, RenewalPredecessor = removed.RenewalPredecessor };
+ _registrations[removed.Demand] = replacement; _byId[replacement.Id] = replacement;
+ TrackSource(removed.Demand);
+ addQueue.Add(replacement);
+ continue;
+ }
+ FinishRefresh(removed.Demand);
+ ReleaseDemand(removed.Demand);
}
- FinishRefresh(removed.Demand);
- ReleaseDemand(removed.Demand);
}
else
{
- if (!pendingCommands.Remove(ack.CommandId, out var expected) || ack.Items.Count != 1 ||
- ack.Items[0].ClientItemId != expected.Id) throw new InvalidDataException("Unexpected snapshot acknowledgement.");
- var response = ack.Items[0];
- if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) throw new InvalidDataException("Invalid item acknowledgement.");
- registration.Handle = response.Handle; _byHandle[response.Handle] = registration;
- EnqueueSnapshot([registration]);
- registration.NeedsChallenge = true;
+ if (!pendingCommands.Remove(ack.CommandId, out var expectedBatch) || ack.Items.Count != expectedBatch.Count)
+ throw new InvalidDataException("Unexpected snapshot acknowledgement.");
+ var owners = new HashSet();
+ for (var i = 0; i < expectedBatch.Count; i++)
+ {
+ var response = ack.Items[i];
+ if (response.ClientItemId != expectedBatch[i].Id) throw new InvalidDataException("Unexpected snapshot acknowledgement.");
+ if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) throw new InvalidDataException("Invalid item acknowledgement.");
+ registration.Handle = response.Handle; _byHandle[response.Handle] = registration;
+ owners.Add(registration);
+ registration.NeedsChallenge = true;
+ if (registration.Removed) removeQueue.Add(registration);
+ }
+ EnqueueSnapshot(owners);
if (freshnessTimer is not null)
{
var milliseconds = Math.Clamp(_registrations.Values.Min(x => x.Demand.MaximumSampleAge.TotalMilliseconds) / 2, 50, 5000);
var interval = TimeSpan.FromMilliseconds(milliseconds);
freshnessTimer.Change(interval, interval);
}
- if (registration.Removed)
- {
- var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
- await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [response.Handle]), route.Token).ConfigureAwait(false);
- }
}
- await ChallengeAsync(route.Token).ConfigureAwait(false);
}
else if (frame is DataSubscriptionControl control)
{
@@ -1828,7 +2002,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (!inSnapshot) throw new InvalidDataException("Snapshot end without begin.");
foreach (var item in pending)
{
- var accepted = Publish(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version, out var validated);
+ var (accepted, validated) = await PublishPacedAsync(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version, route.Token).ConfigureAwait(false);
if (!accepted && item.Registration.Recovery && item.Update.SourceProof is AttemptProof recoveryProof)
{
var recoverySource = recoveryProof.Source;
@@ -1883,7 +2057,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (!item.AgeBounds.Advance(_owner.Clock.GetElapsedTime(ageTimestamp, _owner.Clock.GetTimestamp())).IsFresh(registration.Demand.MaximumSampleAge))
{ ProjectedStreamDiagnostics.Count(item.AgeBounds.Upper is null ? ProjectedStreamDiagnostics.Event.UnknownAge : ProjectedStreamDiagnostics.Event.StaleAge); continue; }
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.FreshAge);
- var source = _owner.GetSource(registration.Demand, _connectionId); if (source is null) throw new InvalidDataException("Source unavailable.");
+ var binding = registration.Demand.CurrentBinding;
+ SourceState source;
+ if (registration.CachedSource is { } cachedSource && ReferenceEquals(registration.CachedBinding, binding) && cachedSource.IsValid)
+ source = cachedSource;
+ else
+ {
+ source = _owner.GetSource(registration.Demand, _connectionId) ?? throw new InvalidDataException("Source unavailable.");
+ registration.CachedSource = source; registration.CachedBinding = binding;
+ }
if (demandSources.TryGetValue(registration.Demand, out var priorSource) && !ReferenceEquals(priorSource, source))
UntrackSource(registration.Demand);
demandSources[registration.Demand] = source;
@@ -1906,14 +2088,14 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// handle ready before its own snapshot barrier ends.
if (!registration.HasBaseline && !registration.AwaitingCurrent) continue;
var recovery = registration.Recovery && registration.AwaitingCurrent;
- var accepted = Publish(registration, recovery ? update with { IsCompleteSnapshot = true } : update, sample.Version, out var validated);
+ var (accepted, validated) = await PublishPacedAsync(registration, recovery ? update with { IsCompleteSnapshot = true } : update, sample.Version, route.Token).ConfigureAwait(false);
if (recovery && (accepted || validated))
{ registration.HasBaseline = true; registration.Recovery = false; registration.AwaitingCurrent = false; FinishRefresh(registration.Demand); }
}
}
}
}
- finally { Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose(); }
+ finally { _frameSlots.Release(); Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose(); }
}
}
}
@@ -1925,6 +2107,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
try { await attemptStop.CancelAsync().ConfigureAwait(false); } catch (Exception) { }
freshnessTimer?.Dispose();
renewalTimer?.Dispose();
+ flushTimer?.Dispose();
try { await Task.WhenAll(renewals.Values).ConfigureAwait(false); } catch (Exception) { }
try { if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
@@ -1936,7 +2119,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
while (_events.Reader.TryRead(out var remaining))
{
if (remaining is RenewalEvent) Interlocked.Increment(ref _owner._renewalTicksHandled);
- else if (remaining is FrameEvent f) { Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); }
+ else if (remaining is FrameEvent f) { _frameSlots.Release(); Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); }
}
lock (_owner._sync) _refreshRequests.Clear();
}
@@ -1976,7 +2159,12 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
source.HasFreshCachedLocked(registration.Demand)) return false;
// A demand disposed since the check above publishes nothing (it is no longer anyone's subscription).
if (!registration.Demand.IsValid) { validated = false; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
- if (_owner._publisher.TryPublish([update]))
+ var outcome = _owner._publisher.TryPublishOrBackpressure([update]);
+ if (outcome == ProjectedPublishOutcome.CapacityExhausted && _capacityRetryAllowed)
+ { _capacityRefused = true; validated = false; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishSink); return false; }
+ if (outcome == ProjectedPublishOutcome.CapacityExhausted)
+ try { update.SourceProof.Invalidate(); } catch (Exception) { } // the bound passed: fail closed as a refusal does
+ if (outcome == ProjectedPublishOutcome.Accepted)
{
if (successor is not null)
{
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs
index b7a6695ba..c3b84a16e 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs
@@ -86,7 +86,7 @@ internal sealed class SamplePartition : IDisposable
Volatile.Write(ref state.Gate, new SourceGate(ticket.Generation, ticket.Binding));
state.AppliedInvalidations = 0;
state.LastApplied = 0; state.Barrier = 0; ReleaseCache(state);
- RecordChange(ticket.Key); return true;
+ RecordChange(state); return true;
}
var charge = SourceCharge(ticket.Key);
if (!_hub.TryTrackSource()) { InvalidatePartition(); return false; }
@@ -151,6 +151,7 @@ internal sealed class SamplePartition : IDisposable
}
Interlocked.Increment(ref gate.Invalidated);
Interlocked.Increment(ref gate.ProducerStamp);
+ Interlocked.Increment(ref state.QuietVersion);
}
finally { Control.EndQuiet(); }
}
@@ -308,7 +309,7 @@ internal sealed class SamplePartition : IDisposable
private void InvalidateSource(SourceState state)
{
Control.BeginQuiet();
- try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); ReleaseCache(state); }
+ try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.QuietVersion); ReleaseCache(state); }
finally { Control.EndQuiet(); }
}
@@ -343,7 +344,7 @@ internal sealed class SamplePartition : IDisposable
{
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead))
{ state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; }
- state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); ReleaseCache(state);
+ state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); Interlocked.Increment(ref state.QuietVersion); ReleaseCache(state);
}
finally { Control.EndQuiet(); }
RequestReclaim();
@@ -429,7 +430,7 @@ internal sealed class SamplePartition : IDisposable
else if (state.Sample is null) state.Readiness = DataReadiness.WaitingForInitialData;
_hub.Resources.Release(p.Charge);
}
- RecordChange(p.Ticket.Key);
+ RecordChange(state);
}
if (!_disposed) ReclaimTombstones();
}
@@ -444,9 +445,11 @@ internal sealed class SamplePartition : IDisposable
lock (_gate) if (_queue.Count == 0 && _mailbox.IsEmpty && _dirty.IsEmpty) return;
}
}
- private void RecordChange(BackingSourceKey key)
+ private void RecordChange(SourceState state)
{
+ var key = state.Ticket.Key;
_watermark++;
+ state.LastChange = _watermark;
if (_changes.Count == _hub.Limits.MaxSnapshotCatchUpItems)
{ _changeIndex.Remove(_changes.First!.Value.Version); _changes.RemoveFirst(); _hub.Resources.Release(ChangeOverhead); }
if (!_hub.Resources.TryReserve(ChangeOverhead)) { InvalidatePartition(); return; }
@@ -578,7 +581,7 @@ internal sealed class SamplePartition : IDisposable
}
}
internal bool CaptureAndRegister(IReadOnlyList tickets, Dictionary items,
- Dictionary interests, out long watermark, out long epoch,
+ Dictionary interests, Dictionary quietVersions, out long watermark, out long epoch,
ref long snapshotCharge, ref long interestCharge, long limit, SnapshotAdmissionScheduler.Permit? admission)
{
lock (_gate)
@@ -592,31 +595,60 @@ internal sealed class SamplePartition : IDisposable
interestCharge += PartitionedSampleHub.ReferenceOverhead;
Interlocked.Increment(ref state.MetadataOwners);
interests.Add(ticket, state);
+ // Read inside the caller's quiet capture window (it re-checks the partition quiet stamp afterwards).
+ quietVersions[ticket] = Interlocked.Read(ref state.QuietVersion);
}
return true;
}
}
internal void ReleaseInterest(object source) => ReleaseMetadataOwner((SourceState)source);
+ /// #994 (R-9): the source's quiet version (see ); lock-free.
+ internal static long QuietVersionOf(object source) => Interlocked.Read(ref ((SourceState)source).QuietVersion);
internal bool ReadInterestChanges(long epoch, ref long position, IReadOnlyDictionary tickets,
- int maximum, List changes, out int scanned)
+ int maximum, List changes, out int scanned) =>
+ ReadInterestChanges(epoch, ref position, tickets, maximum, int.MaxValue, changes, out scanned, out _);
+
+ ///
+ /// #994 (R-3): reads this lease's changes since . At most
+ /// changes of ITS OWN tickets are returned and at most partition entries walked
+ /// (unrelated traffic no longer consumes the match budget); says the cursor is still behind.
+ /// When the bounded history no longer reaches the cursor (busy unrelated sources rolled it off) the lease catches
+ /// up from each own source's — O(own tickets) — instead of resetting the stream.
+ ///
+ internal bool ReadInterestChanges(long epoch, ref long position, IReadOnlyDictionary tickets,
+ int maximumMatches, int maximumScanned, List changes, out int scanned, out bool more)
{
- scanned = 0;
+ scanned = 0; more = false;
lock (_gate)
{
if (_disposed || epoch != _epoch) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestEpoch); return false; }
if (position == _watermark) return true;
- if (!_changeIndex.TryGetValue(position + 1, out var node)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestHistoryGap); return false; }
- while (node is not null && scanned < maximum)
+ if (!_changeIndex.TryGetValue(position + 1, out var node))
+ {
+ SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestHistoryGap);
+ foreach (var ticket in tickets.Values)
+ {
+ scanned++;
+ if (!_sources.TryGetValue(ticket.Key, out var state) || state.LastChange <= position) continue;
+ if (!Current(ticket, out _)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestTicket); return false; }
+ changes.Add(new(ticket, state.LastChange));
+ }
+ position = _watermark;
+ return true;
+ }
+ var matched = 0;
+ while (node is not null && matched < maximumMatches && scanned < maximumScanned)
{
var change = node.Value; position = change.Version; scanned++;
if (tickets.TryGetValue(change.Key, out var ticket))
{
if (!Current(ticket, out _)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestTicket); return false; }
- changes.Add(new(ticket, change.Version));
+ changes.Add(new(ticket, change.Version)); matched++;
}
node = node.Next;
}
+ more = position != _watermark;
return true;
}
}
@@ -678,6 +710,13 @@ internal sealed class SamplePartition : IDisposable
public bool Removed; public DataReadiness Readiness = DataReadiness.WaitingForInitialData;
public DataSample? Sample; public long SampleCharge; public long Received;
public long LastApplied; public long Barrier; public long InvalidationVersion; public Pending? Dirty;
+ /// #994 (R-3): the partition watermark of this source's latest recorded change (under the partition gate).
+ public long LastChange;
+ ///
+ /// #994 (R-9): bumped INSIDE every quiet bracket that invalidates this source (Signal, InvalidateSource, TryRemove),
+ /// so an interest lease can tell its own sources' invalidation from a sibling's partition-wide quiet bump.
+ ///
+ public long QuietVersion;
}
private sealed class Pending
{
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs
index 308db6171..e1af65946 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs
@@ -12,12 +12,14 @@ public sealed class SourceInterestLease : IDisposable
internal readonly SamplePartition Partition = partition;
internal long Position = position;
internal readonly long Epoch = epoch;
- internal readonly long QuietControl = quietControl;
+ // #994 (R-9): advanced (under the lease gate) once a partition quiet bump is proven to concern only OTHER sources.
+ internal long QuietControl = quietControl;
internal readonly Dictionary Tickets = tickets;
}
private readonly object _gate = new();
private readonly PartitionedSampleHub _hub;
private readonly Dictionary _owners;
+ private readonly Dictionary _quietVersions;
private Cursor[] _cursors;
private readonly long _routingEpoch;
private long _charge;
@@ -27,9 +29,9 @@ public sealed class SourceInterestLease : IDisposable
internal SourceInterestLease(PartitionedSampleHub hub,
Dictionary owners,
IReadOnlyDictionary watermarks, IReadOnlyDictionary epochs, IReadOnlyDictionary quietControls,
- long routingEpoch, long charge, CancellationToken cancellationToken)
+ Dictionary quietVersions, long routingEpoch, long charge, CancellationToken cancellationToken)
{
- _hub = hub; _owners = owners; _routingEpoch = routingEpoch; _charge = charge;
+ _hub = hub; _owners = owners; _quietVersions = quietVersions; _routingEpoch = routingEpoch; _charge = charge;
_cursors = owners.GroupBy(x => x.Value.Partition.Id).Select(group => new Cursor(group.First().Value.Partition,
watermarks[group.Key], epochs[group.Key], quietControls[group.Key], group.ToDictionary(x => x.Key.Key, x => x.Key))).ToArray();
_cancellation = cancellationToken.Register(static state => ((SourceInterestLease)state!).Dispose(), this);
@@ -39,6 +41,7 @@ public sealed class SourceInterestLease : IDisposable
lock (_gate)
{
if (_released != 0 || !_owners.Remove(ticket, out var owner)) return false;
+ _quietVersions.Remove(ticket);
foreach (var cursor in _cursors) cursor.Tickets.Remove(ticket.Key);
_cursors = _cursors.Where(cursor => cursor.Tickets.Count != 0).ToArray();
if (_next >= _cursors.Length) _next = 0;
@@ -52,33 +55,63 @@ public sealed class SourceInterestLease : IDisposable
}
public bool IsReset
{
- get
+ get { lock (_gate) return IsResetLocked(); }
+ }
+
+ ///
+ /// #994 (R-9): a partition's quiet stamp moves for ANY source's invalidation (including ordinary lock contention on a
+ /// sibling). It resets this lease only when one of its OWN sources was invalidated (its quiet version moved) or its
+ /// binding was retired; otherwise the cursor adopts the new stamp. An in-progress bracket is undecided, not a reset —
+ /// the next read decides it. Partition-wide invalidation still resets through the partition epoch.
+ ///
+ private bool IsResetLocked()
+ {
+ if (_released != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) return true;
+ foreach (var cursor in _cursors)
{
- if (Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) return true;
- foreach (var cursor in Volatile.Read(ref _cursors))
- if (!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestQuiet); return true; }
- return Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch;
+ var quiet = cursor.Partition.Control.Quiet;
+ if (quiet.Matches(cursor.QuietControl)) continue;
+ if (!quiet.TryCapture(out var now)) continue;
+ foreach (var ticket in cursor.Tickets.Values)
+ {
+ if (!_owners.TryGetValue(ticket, out var owner) || !_quietVersions.TryGetValue(ticket, out var captured) ||
+ SamplePartition.QuietVersionOf(owner.Source) != captured || !cursor.Partition.IsTicketCurrentNonBlocking(ticket))
+ { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestQuiet); return true; }
+ }
+ cursor.QuietControl = now;
}
+ return _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch;
}
/// Scans at most maximum retained partition changes, returning false on a gap or epoch reset.
- public bool TryReadChanges(int maximum, out IReadOnlyList changes)
+ public bool TryReadChanges(int maximum, out IReadOnlyList changes) =>
+ TryReadChanges(maximum, maximum, out changes, out _);
+
+ ///
+ /// #994 (R-3): returns at most changes of this lease's own sources, walking at most
+ /// partition entries; is true when a cursor is still behind
+ /// (the caller re-queues instead of waiting for its next timer tick).
+ ///
+ public bool TryReadChanges(int maximumMatches, int maximumScanned, out IReadOnlyList changes, out bool more)
{
- if (maximum <= 0) throw new ArgumentOutOfRangeException(nameof(maximum));
+ if (maximumMatches <= 0 || maximumScanned <= 0) throw new ArgumentOutOfRangeException(nameof(maximumMatches));
+ more = false;
lock (_gate)
{
var result = new List();
changes = result;
- if (IsReset) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); return false; }
+ if (IsResetLocked()) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); return false; }
var scanned = 0;
- for (var visited = 0; visited < _cursors.Length && scanned < maximum; visited++)
+ for (var visited = 0; visited < _cursors.Length; visited++)
{
var cursor = _cursors[_next]; _next = (_next + 1) % _cursors.Length;
+ if (scanned >= maximumScanned || result.Count >= maximumMatches) { more = true; break; }
if (!cursor.Partition.ReadInterestChanges(cursor.Epoch, ref cursor.Position, cursor.Tickets,
- maximum - scanned, result, out var used)) { Release(); result.Clear(); return false; }
- scanned += used;
+ maximumMatches - result.Count, maximumScanned - scanned, result, out var used, out var behind))
+ { Release(); result.Clear(); return false; }
+ scanned += used; more |= behind;
}
- if (IsReset) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); result.Clear(); return false; }
+ if (IsResetLocked()) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); result.Clear(); return false; }
return true;
}
}
@@ -89,7 +122,7 @@ public sealed class SourceInterestLease : IDisposable
_cancellation.Unregister();
var count = _owners.Count;
foreach (var owner in _owners.Values) owner.Partition.ReleaseInterest(owner.Source);
- _owners.Clear(); _cursors = [];
+ _owners.Clear(); _quietVersions.Clear(); _cursors = [];
_hub.Resources.Release(_charge); _hub.UntrackInterestItems(count);
}
_hub.ForgetInterest(this);
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/WriteOperationRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/WriteOperationRegistry.cs
index a8533b010..09af50f62 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/WriteOperationRegistry.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/WriteOperationRegistry.cs
@@ -20,6 +20,7 @@ public sealed class WriteOperationRegistry
private readonly TimeSpan _retention;
private readonly TimeProvider _clock;
private long _retainedBytes;
+ private long _lastPrune;
///
/// A2b security review: the most entries one principal may hold at once (null ⇒ , i.e.
@@ -52,14 +53,28 @@ public sealed class WriteOperationRegistry
var bytes = 256L + 2L * principal.Length + 2L * operationId.Length + semanticHash.Length;
lock (_gate)
{
- Prune();
+ // #994 (R-21): the full retirement sweep runs at most once per prune interval, or when the table would refuse —
+ // it used to copy and scan the whole table on every claim (~retention × writes/s entries, under this lock). An
+ // expired entry met by key is retired on the spot, so a reused operation id past retention is a fresh owner exactly
+ // as before, and capacity is never refused while a retirable entry remains.
+ var now = _clock.GetTimestamp();
+ if (_clock.GetElapsedTime(_lastPrune, now) >= PruneInterval) Prune(now);
var key = (principal, operationId);
if (_entries.TryGetValue(key, out var existing))
- return existing.Hash.AsSpan().SequenceEqual(semanticHash.Span)
- ? new(WriteClaimKind.Existing, existing.Claim) : new(WriteClaimKind.Conflict);
+ {
+ if (!existing.Claim.CanRetire(now, _retention))
+ return existing.Hash.AsSpan().SequenceEqual(semanticHash.Span)
+ ? new(WriteClaimKind.Existing, existing.Claim) : new(WriteClaimKind.Conflict);
+ Remove(key, existing);
+ }
_perPrincipal.TryGetValue(principal, out var held);
if (_entries.Count >= _maxEntries || held >= _maxEntriesPerPrincipal || bytes > _maxBytes - _retainedBytes)
- return new(WriteClaimKind.Capacity);
+ {
+ Prune(now);
+ _perPrincipal.TryGetValue(principal, out held);
+ if (_entries.Count >= _maxEntries || held >= _maxEntriesPerPrincipal || bytes > _maxBytes - _retainedBytes)
+ return new(WriteClaimKind.Capacity);
+ }
var claim = new WriteClaim(_clock);
_entries.Add(key, new Entry(semanticHash.ToArray(), claim, bytes));
_perPrincipal[principal] = held + 1;
@@ -101,10 +116,13 @@ public sealed class WriteOperationRegistry
}
}
- private void Prune()
+ private TimeSpan PruneInterval => _retention < TimeSpan.FromSeconds(4) ? _retention / 4 : TimeSpan.FromSeconds(1);
+
+ private void Prune(long now)
{
- var now = _clock.GetTimestamp();
- foreach (var pair in _entries.ToArray())
+ _lastPrune = now;
+ // Removing during enumeration is supported by Dictionary<,> (no copy of the table).
+ foreach (var pair in _entries)
{
if (!pair.Value.Claim.CanRetire(now, _retention)) continue;
Remove(pair.Key, pair.Value);
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkHierarchyTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkHierarchyTests.cs
index 10346b7ae..e744ada96 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkHierarchyTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkHierarchyTests.cs
@@ -132,6 +132,59 @@ public sealed class GrpcDataSdkHierarchyTests : IDisposable
1, null, null, false, elementKind);
return new(realm, ProjectedDataIds.Identifier("mapping", origin), parent, metadata, 1, () => true);
}
+ // #994 (U-11): removing a projected anchor tombstoned its descendants' monitored nodes but never the anchor's OWN. The SDK
+ // reuses a MonitoredNodes entry by NodeId, so an item left on the dead folder would capture every later item on a
+ // re-created anchor of the same NodeId (delivery requires the entry's Node to BE the live node). Likewise a root-leaf swap
+ // replaces the anchor folder with a variable under the same NodeId.
+ [Theory, Trait("Issue", "994")]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task U11_an_anchor_removal_or_root_leaf_swap_tombstones_the_anchor_s_own_monitored_node(bool swap)
+ {
+ var started = await StartAsync();
+ try
+ {
+ var manager = started.Server.NodeManager!;
+ manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
+ var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
+ var origin = new DataAddress("origin", "urn:raw", "string", "anchor-u11");
+ var identifier = ProjectedDataIds.Identifier("mapping", origin);
+ var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, identifier, parent, "Branch", "Plant/Branch", "mapping", 1, () => true);
+ manager.TryEnsureProjectedAnchor(anchor, out var id).ShouldBeTrue();
+ var folder = ((NodeHandle)manager.GetManagerHandle(id!.Value)!).Node.ShouldBeOfType();
+ AttachMonitoredNode(manager, folder); // what a client's event/attribute item on the anchor leaves behind
+ manager.IsNodeMonitored(id.Value).ShouldBeTrue("positive control: the anchor carries a monitored node");
+ if (swap)
+ {
+ var metadata = new DataMetadata(new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Branch"), "Leaf", "Variable",
+ DataValueKind.Int32, -1, [], false, DataOperations.Browse | DataOperations.Read, 1, null, null, false);
+ var leaf = new ProjectedVariableDefinition(DataRealm.Raw, identifier, id.Value, metadata, 1, () => true);
+ ((IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager)).TryApplyRootLeaf(id.Value, leaf, () => true).ShouldBeTrue();
+ }
+ else manager.TryRemoveProjectedAnchor(id.Value, anchor).ShouldBeTrue();
+ manager.IsNodeMonitored(id.Value).ShouldBeFalse("no monitored node may keep pointing at the dead anchor folder");
+ }
+ finally { await started.Host.DisposeAsync(); }
+ }
+
+ private static void AttachMonitoredNode(OtOpcUaNodeManager manager, NodeState node)
+ {
+ const System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public |
+ System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy;
+ var server = typeof(CustomNodeManager2).GetProperty("Server", flags)!.GetValue(manager)!;
+ // The entry is all the removal path looks at; its node-manager back-reference is never called here.
+ var asyncManager = System.Reflection.DispatchProxy.Create();
+ var monitored = Activator.CreateInstance(typeof(MonitoredNode2), asyncManager, server, node, false)!;
+ var nodes = typeof(CustomNodeManager2).GetProperty("MonitoredNodes", flags)!.GetValue(manager)!;
+ lock (manager.Lock) nodes.GetType().GetProperty("Item")!.SetValue(nodes, monitored, [node.NodeId]);
+ }
+
+ public class InertProxy : System.Reflection.DispatchProxy
+ {
+ protected override object? Invoke(System.Reflection.MethodInfo? targetMethod, object?[]? args) =>
+ targetMethod?.ReturnType is { IsValueType: true } type && type != typeof(void) ? Activator.CreateInstance(type) : null;
+ }
+
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> StartAsync() =>
await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs
index 69bc0356f..4b113fe50 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs
@@ -221,6 +221,34 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable
computes.ShouldBe(1);
}
+ // #994 (U-13): removing a condition purges exactly ITS cached verdicts (via a per-condition identity index — it used to scan
+ // every cached verdict under the manager Lock, ~K × 65,536 comparisons for a K-condition removal).
+ [Fact, Trait("Issue", "994")]
+ public void U13_removing_conditions_purges_exactly_their_verdicts_and_keeps_the_rest()
+ {
+ var registry = new ProjectedConditionRegistry();
+ var conditions = Enumerable.Range(0, 1000).Select(i =>
+ new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c" + i, 9) }, "conn", "k" + i)).ToArray();
+ foreach (var condition in conditions) registry.Add(condition);
+ var identities = Enumerable.Range(0, 60).Select(_ => new object()).ToArray();
+ var now = DateTimeOffset.UtcNow;
+ foreach (var condition in conditions)
+ foreach (var identity in identities) registry.Verdict(identity, condition, 1, now, null, () => false);
+ registry.VerdictCountForTests.ShouldBe(60_000);
+ var started = System.Diagnostics.Stopwatch.GetTimestamp();
+ foreach (var condition in conditions.Take(500)) registry.Remove(condition);
+ var elapsed = System.Diagnostics.Stopwatch.GetElapsedTime(started);
+ registry.VerdictCountForTests.ShouldBe(30_000);
+ // A survivor is still served from cache; a removed-and-re-added one is decided afresh.
+ var computes = 0;
+ registry.Verdict(identities[0], conditions[999], 1, now, null, () => { computes++; return true; }).ShouldBeFalse();
+ computes.ShouldBe(0);
+ registry.Add(conditions[0]);
+ registry.Verdict(identities[0], conditions[0], 1, now, null, () => { computes++; return true; }).ShouldBeTrue();
+ computes.ShouldBe(1);
+ elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(5), "500 removals against 60k verdicts are bounded per condition");
+ }
+
[Fact]
public void Issue936_r1_S3_S4_admission_is_recorded_lazily_per_credential_and_survives_a_new_identity_object()
{
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/CohortScaleFixture.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/CohortScaleFixture.cs
new file mode 100644
index 000000000..d42ba7bed
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/CohortScaleFixture.cs
@@ -0,0 +1,244 @@
+using System.Collections.Concurrent;
+using Opc.Ua;
+using Shouldly;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
+using ZB.MOM.WW.OtOpcUa.Core.Authorization;
+using ZB.MOM.WW.OtOpcUa.OpcUaServer;
+using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
+using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
+
+namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
+
+///
+/// #994 (R-2/R-7/R-13): a consumer holding N projected demands, every one
+/// subscribed through ONE cohort onto a REAL origin (real
+/// , default 128 commands/s per principal) — the end-to-end path the
+/// per-item command loop broke. Values are counted per local identifier as they reach the publisher.
+///
+internal sealed class CohortScaleFixture : IFederatedProjectionCatalog, IProjectedNodeLookup, IGrpcDataAdapterConnectionSource,
+ IProjectedValuePublisher, IDisposable
+{
+ internal readonly LocalDataFixture Origin;
+ internal readonly SubscriptionTransportCapacity Capacity;
+ internal readonly DeferredSubscriptionDemand OriginDemand = new();
+ private readonly DataOperationPolicy _policy;
+ internal readonly RoleCarryingUserIdentity Caller;
+ internal readonly NodeId[] NodeIds;
+ private readonly Dictionary _definitions = new();
+ private readonly Dictionary _proofs = new(StringComparer.Ordinal);
+ internal readonly ConcurrentDictionary Baselines = new(StringComparer.Ordinal);
+ internal readonly ConcurrentDictionary Latest = new(StringComparer.Ordinal);
+ internal int Retired, Publishes, Opens;
+ /// When set, TryPublish answers false (a capacity-refusing sink).
+ #pragma warning disable CS0649 // set by individual tests
+ internal volatile bool RefusePublish;
+ internal Func? PublishGate;
+#pragma warning restore CS0649
+ internal readonly ConcurrentQueue Commands = new();
+ private readonly ConcurrentQueue _streams = new();
+ private DataSubscriptionSession? _session;
+ internal DataSubscriptionSession? Session => Volatile.Read(ref _session);
+
+ internal readonly int MaxBatchItems;
+ internal CohortScaleFixture(int items, int maxCommandsPerSecond = 128, int maxBatchItems = 100)
+ {
+ MaxBatchItems = maxBatchItems;
+ Capacity = new SubscriptionTransportCapacity(64, 16, 256L * 1024 * 1024, maxCommandsPerSecond: maxCommandsPerSecond);
+ var limits = new SubscriptionSessionLimits(128, 64, 1024 * 1024, TimeSpan.FromMinutes(5));
+ LocalDataFixture? peer = null;
+ Origin = new LocalDataFixture(additionalRawNodes: items, servingGeneration: 1, maxMonitoredItems: items + 16,
+ maxBatchItems: maxBatchItems, maxMessageBytes: 64 * 1024 * 1024, subscriptionFreshnessChallenges: true, hubBytes: 256L * 1024 * 1024,
+ targetSubscriptions: (context, target) => new CapturingService(this,
+ new LocalSubscriptionService(peer!.Services, context, target, OriginDemand, limits, Capacity)));
+ peer = Origin;
+ OriginDemand.Accept();
+ Origin.Publish(42);
+ _policy = new(Origin.Authority, new TriePermissionEvaluator(Origin.Authority.Tries, Origin.Clock), Origin.Clock);
+ Caller = new(new AnonymousIdentityToken(), [], Origin.Context.PrincipalId, Origin.Context.ApiKeyId,
+ Origin.Context.CredentialVersion, Origin.Context.CredentialExpiresUtc);
+ var serving = Origin.Serving;
+ var lease = new MetadataAuthorityLease(serving, new(1, 1, TimeSpan.FromSeconds(15)), Origin.Clock.GetTimestamp(),
+ TimeSpan.FromSeconds(15), TimeSpan.Zero, Origin.Clock);
+ var authority = Origin.Activation.CaptureAuthority();
+ NodeIds = new NodeId[items];
+ for (var i = 0; i < items; i++)
+ {
+ var origin = Origin.Raw with { Address = Origin.Raw.Address with { Identifier = Origin.Raw.Address.Identifier + i }, Subject = Origin.Raw.Subject + i };
+ var mapped = origin with { MappingId = "mapping", MappingRevision = 1, Subject = "Plant/branch/Speed" + i };
+ var subject = new MappedNamespaceSubject(mapped, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw,
+ Segments = ["Plant", "branch", "Speed" + i] }, ["folder"], serving, DataOperations.Subscribe, false);
+ var metadata = new DataMetadata(mapped, "Speed" + i, "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Subscribe, 1, null, null, false, Serving: serving);
+ var proof = new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", origin.Address), metadata, subject,
+ new([subject], 1, authority), lease, 1, metadata with { View = origin }, TimeSpan.FromSeconds(30));
+ var nodeId = new NodeId("projected-" + i, 2);
+ NodeIds[i] = nodeId;
+ _proofs[proof.LocalIdentifier] = proof;
+ _definitions[nodeId] = new(DataRealm.Raw, proof.LocalIdentifier, new NodeId("parent", 2), metadata, 1, () => true);
+ }
+ }
+
+ internal ProjectedDataAccess Create(int maxDemands) =>
+ new(this, this, this, _ => "link", _policy, this, Origin.Clock, new(maxDemands, 8, 64L * 1024 * 1024, 4));
+
+ internal IProjectedDemandLease[] AcquireAll(ProjectedDataAccess access)
+ {
+ var demands = new IProjectedDemandLease[NodeIds.Length];
+ for (var i = 0; i < NodeIds.Length; i++)
+ {
+ access.TryAcquire(NodeIds[i], Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue();
+ demands[i] = demand!;
+ }
+ return demands;
+ }
+
+ internal async Task WaitForAsync(Func condition, TimeSpan timeout, string because)
+ {
+ var deadline = DateTime.UtcNow + timeout;
+ while (!condition())
+ {
+ if (DateTime.UtcNow > deadline) throw new ShouldAssertException(because + " | " +
+ string.Join(" ", ProjectedStreamDiagnostics.Capture().Where(x => x.Value != 0).Select(x => x.Key + "=" + x.Value)) +
+ " | opens=" + Opens + " commands=" + string.Join(",", Commands.GroupBy(c => c.GetType().Name)
+ .Select(g => g.Key + "x" + g.Count() + "(" + g.Sum(CommandItems) + " items)")));
+ await Task.Delay(10);
+ }
+ }
+
+ private static int CommandItems(DataSubscriptionCommand command) => command switch
+ {
+ OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count, RemoveSubscriptionItems r => r.Items.Count,
+ ChallengeSubscriptionFreshness c => c.Items.Count, _ => 0
+ };
+
+ ///
+ /// Runs the fixture clock at about half real speed until disposed: the cohort's command pacer (32/s) and the origin's
+ /// per-second command window both read this clock, so a long open stalls on a frozen manual clock.
+ ///
+ internal IAsyncDisposable PumpClock()
+ {
+ var stop = new CancellationTokenSource();
+ var pump = Task.Run(async () =>
+ {
+ while (!stop.IsCancellationRequested)
+ {
+ try { await Task.Delay(20, stop.Token); } catch (OperationCanceledException) { break; }
+ Origin.Clock.Advance(TimeSpan.FromMilliseconds(10));
+ }
+ });
+ return new ClockPump(stop, pump);
+ }
+ private sealed class ClockPump(CancellationTokenSource stop, Task pump) : IAsyncDisposable
+ {
+ public async ValueTask DisposeAsync() { await stop.CancelAsync(); await pump; stop.Dispose(); }
+ }
+
+ internal void PublishVersion(long version, int value)
+ {
+ HubTest.Publish(Origin.Hub, Origin.Ticket, version, value);
+ Origin.Hub.ProcessPending();
+ }
+
+ /// Drops the current physical stream (origin restart / failover) so the cohort must re-open everything.
+ internal async Task DropStreamAsync()
+ {
+ foreach (var stream in _streams.ToArray()) await stream.DisposeAsync();
+ }
+
+ public TimeProvider Clock => Origin.Clock;
+ public event Action? Invalidated { add { } remove { } }
+ public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => throw new NotSupportedException();
+ public Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
+ public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) =>
+ _proofs.TryGetValue(localId, out proof) && realm == DataRealm.Raw;
+ public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin)
+ {
+ pin = _proofs.ContainsKey(localId) ? new NoopPin() : null;
+ return pin is not null;
+ }
+ public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _definitions.TryGetValue(nodeId, out definition);
+ public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) { nodeId = null; return false; }
+ public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
+ ValueTask.FromResult(new Lease(Origin.Connection()));
+ public bool TryBind(ProjectedValueRoute route) => true;
+ /// #994 (R-10): this many publications are answered CapacityExhausted (a momentarily full sink).
+ internal int CapacityRefusals;
+ public ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList updates)
+ {
+ if (Volatile.Read(ref CapacityRefusals) > 0 && Interlocked.Decrement(ref CapacityRefusals) >= 0) return ProjectedPublishOutcome.CapacityExhausted;
+ return TryPublish(updates) ? ProjectedPublishOutcome.Accepted : ProjectedPublishOutcome.Refused;
+ }
+ public bool TryPublish(IReadOnlyList updates)
+ {
+ if (RefusePublish) return false;
+ foreach (var update in updates)
+ {
+ if (PublishGate is { } gate && !gate(update)) return false;
+ Interlocked.Increment(ref Publishes);
+ if (update.IsCompleteSnapshot) Baselines.AddOrUpdate(update.Route.LocalIdentifier, 1, (_, count) => count + 1);
+ Latest[update.Route.LocalIdentifier] = update.SourceVersion ?? 0;
+ }
+ return true;
+ }
+ public void Retire(ProjectedValueRoute route) => Interlocked.Increment(ref Retired);
+ public void Dispose() => Origin.Dispose();
+
+ private sealed class NoopPin : IDisposable { public void Dispose() { } }
+ private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
+ {
+ public IDataConnection Connection => connection;
+ public CancellationToken CancellationToken => CancellationToken.None;
+ public ValueTask DisposeAsync() => connection.DisposeAsync();
+ }
+ private sealed class CapturingService(CohortScaleFixture owner, IDataSubscriptionService inner) : IDataSubscriptionService
+ {
+ public async Task SubscribeAsync(CancellationToken cancellationToken)
+ {
+ var stream = await inner.SubscribeAsync(cancellationToken);
+ Interlocked.Increment(ref owner.Opens);
+ if (stream is DataSubscriptionSession session) Volatile.Write(ref owner._session, session);
+ var wrapped = new Recording(owner, stream);
+ owner._streams.Enqueue(wrapped);
+ return wrapped;
+ }
+ }
+ private sealed class Recording(CohortScaleFixture owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport, IDataSubscriptionCommandLimits,
+ IDataSubscriptionProvenance
+ {
+ public ServingIdentity Serving => owner.Origin.Serving;
+ // The origin was built with subscriptionFreshnessChallenges: true (as LocalDataRuntimeComposition is).
+ public bool SupportsFreshnessChallenges => true;
+ public int FreshnessMaxItems => owner.MaxBatchItems;
+ public int MaxCommandItems => (inner as IDataSubscriptionCommandLimits)?.MaxCommandItems ?? owner.MaxBatchItems;
+ private readonly ConcurrentDictionary _challenges = new(StringComparer.Ordinal);
+ public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
+ {
+ owner.Commands.Enqueue(command);
+ if (command is ChallengeSubscriptionFreshness challenge) _challenges[challenge.CommandId] = owner.Clock.GetTimestamp();
+ return inner.SendAsync(command, cancellationToken);
+ }
+ // Mirrors GrpcDataConnection.RemoteSubscription: a challenged value's upper age bound is its origin lower bound plus the
+ // consumer-side elapsed time since the challenge was sent (the local session leaves Upper unknown).
+ public async IAsyncEnumerable ReadAllAsync(
+ [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
+ {
+ await foreach (var frame in inner.ReadAllAsync(cancellationToken))
+ {
+ if (frame is not DataSubscriptionValues values) { yield return frame; continue; }
+ var bounded = new List(values.Items.Count);
+ foreach (var item in values.Items)
+ {
+ var bounds = item.AgeBounds; long? observed = null;
+ if (item.FreshnessChallengeId is { } nonce && _challenges.TryGetValue(nonce, out var start) && bounds.Lower is { } lower)
+ {
+ observed = owner.Clock.GetTimestamp();
+ bounds = new(bounds.Lower, lower + owner.Clock.GetElapsedTime(start, observed.Value));
+ }
+ bounded.Add(item with { Sample = item.Sample with { Value = item.Sample.Value.Retain() }, AgeBounds = bounds,
+ FreshnessObservedTimestamp = observed });
+ }
+ yield return new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot, bounded, values);
+ }
+ }
+ public ValueTask DisposeAsync() => inner.DisposeAsync();
+ }
+}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCohortScaleTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCohortScaleTests.cs
new file mode 100644
index 000000000..804a3a937
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCohortScaleTests.cs
@@ -0,0 +1,140 @@
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
+using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
+
+namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
+
+/// #994: projected-cohort scaling against a real origin session (review 2026-12-02 R-2, R-7, R-13).
+public sealed class GrpcDataCohortScaleTests
+{
+ [Fact(Timeout = 60000), Trait("Issue", "994")]
+ public async Task R2_a_300_item_cohort_opens_against_the_origin_command_rate_and_every_item_gets_its_baseline()
+ {
+ using var fixture = new CohortScaleFixture(300);
+ using var access = fixture.Create(1024);
+ var demands = fixture.AcquireAll(access);
+ try
+ {
+ foreach (var demand in demands) access.StartSubscription(demand, TimeSpan.FromSeconds(1)).ShouldBeTrue();
+ await fixture.WaitForAsync(() => fixture.Baselines.Count == 300, TimeSpan.FromSeconds(30),
+ $"every item must reach its first value; baselines={fixture.Baselines.Count} opens={fixture.Opens} commands={fixture.Commands.Count}");
+ fixture.Opens.ShouldBe(1, "one physical stream carries the whole cohort");
+ fixture.Commands.Count.ShouldBeLessThan(128, "the open stays inside the origin's per-principal command rate");
+ }
+ finally { foreach (var demand in demands) demand.Dispose(); }
+ }
+
+ [Fact(Timeout = 60000), Trait("Issue", "994")]
+ public async Task R2_a_large_cohort_re_establishes_after_a_stream_drop()
+ {
+ using var fixture = new CohortScaleFixture(300);
+ using var access = fixture.Create(1024);
+ var demands = fixture.AcquireAll(access);
+ try
+ {
+ foreach (var demand in demands) access.StartSubscription(demand, TimeSpan.FromSeconds(1)).ShouldBeTrue();
+ await fixture.WaitForAsync(() => fixture.Baselines.Count == 300, TimeSpan.FromSeconds(30), "initial open");
+ fixture.Baselines.Clear();
+ // The origin's rate window is per second of the fixture clock: the re-open happens in the same window.
+ await fixture.DropStreamAsync();
+ await fixture.WaitForAsync(() => fixture.Baselines.Count == 300, TimeSpan.FromSeconds(30),
+ $"every item must be re-baselined after the drop; baselines={fixture.Baselines.Count} opens={fixture.Opens}");
+ fixture.Opens.ShouldBeGreaterThanOrEqualTo(2, "the origin may still hold the dropped session's interests for one retry");
+ }
+ finally { foreach (var demand in demands) demand.Dispose(); }
+ }
+
+ [Fact(Timeout = 60000), Trait("Issue", "994")]
+ public async Task R2_two_items_in_one_cohort_both_reach_the_origin()
+ {
+ // Positive control for the batch path at its smallest: two items added after the open (separate StartSubscription calls).
+ using var fixture = new CohortScaleFixture(2);
+ using var access = fixture.Create(16);
+ var demands = fixture.AcquireAll(access);
+ try
+ {
+ access.StartSubscription(demands[0], TimeSpan.FromSeconds(1)).ShouldBeTrue();
+ await fixture.WaitForAsync(() => fixture.Baselines.Count == 1, TimeSpan.FromSeconds(10), "first item");
+ access.StartSubscription(demands[1], TimeSpan.FromSeconds(1)).ShouldBeTrue();
+ await fixture.WaitForAsync(() => fixture.Baselines.Count == 2, TimeSpan.FromSeconds(10),
+ $"the second item joins the same origin stream; opens={fixture.Opens} commands={string.Join(",", fixture.Commands.Select(c => c.GetType().Name))}");
+ fixture.Opens.ShouldBe(1);
+ }
+ finally { foreach (var demand in demands) demand.Dispose(); }
+ }
+
+ [Fact(Timeout = 60000), Trait("Issue", "994")]
+ public async Task R7_removing_one_item_while_the_frame_backlog_is_full_keeps_every_sibling_demand_live()
+ {
+ using var fixture = new CohortScaleFixture(8);
+ using var access = fixture.Create(16);
+ var demands = fixture.AcquireAll(access);
+ using var blocked = new ManualResetEventSlim(true);
+ var entered = 0;
+ fixture.PublishGate = _ => { Interlocked.Increment(ref entered); blocked.Wait(TimeSpan.FromSeconds(20)); return true; };
+ try
+ {
+ foreach (var demand in demands) access.StartSubscription(demand, TimeSpan.FromMilliseconds(100)).ShouldBeTrue();
+ await fixture.WaitForAsync(() => fixture.Baselines.Count == 8, TimeSpan.FromSeconds(20), "initial baselines");
+ // Stall the cohort's event loop inside a publish, then let the origin keep producing frames so the pump fills
+ // the cohort's frame backlog behind it.
+ blocked.Reset();
+ var stalled = Volatile.Read(ref entered);
+ fixture.PublishVersion(2, 1000); fixture.Origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
+ await fixture.WaitForAsync(() => Volatile.Read(ref entered) > stalled, TimeSpan.FromSeconds(10), "the loop is stalled in a publish");
+ for (var version = 3; version < 80; version++)
+ { fixture.PublishVersion(version, 1000 + version); fixture.Origin.Clock.Advance(TimeSpan.FromMilliseconds(40)); await Task.Delay(5, TestContext.Current.CancellationToken); }
+ await Task.Delay(500, TestContext.Current.CancellationToken);
+ demands[0].Dispose();
+ await Task.Delay(200, TestContext.Current.CancellationToken);
+ blocked.Set();
+ foreach (var sibling in demands.Skip(1)) sibling.IsValid.ShouldBeTrue("a sibling demand must survive one item's removal");
+ // ...and keeps delivering: a later value reaches every sibling.
+ fixture.Latest.Clear();
+ fixture.PublishVersion(100, 5000); fixture.Origin.Clock.Advance(TimeSpan.FromMilliseconds(200));
+ await fixture.WaitForAsync(() => demands.Skip(1).All(d => fixture.Latest.ContainsKey(d.LocalIdentifier)),
+ TimeSpan.FromSeconds(20), $"siblings keep receiving values; latest={fixture.Latest.Count}");
+ }
+ finally { blocked.Set(); foreach (var demand in demands) demand.Dispose(); }
+ }
+
+ [Fact(Timeout = 60000), Trait("Issue", "994")]
+ public async Task R10_a_capacity_refused_sample_is_retried_without_invalidating_the_source_or_reopening_the_stream()
+ {
+ using var fixture = new CohortScaleFixture(4);
+ using var access = fixture.Create(16);
+ var demands = fixture.AcquireAll(access);
+ try
+ {
+ fixture.CapacityRefusals = 20; // the local sink is full for the first 20 publications (about 200 ms of backpressure)
+ foreach (var demand in demands) access.StartSubscription(demand, TimeSpan.FromSeconds(1)).ShouldBeTrue();
+ await fixture.WaitForAsync(() => fixture.Baselines.Count == 4, TimeSpan.FromSeconds(20),
+ $"every baseline is delivered once the sink drains; refusals left={fixture.CapacityRefusals}");
+ fixture.CapacityRefusals.ShouldBeLessThanOrEqualTo(0);
+ fixture.Retired.ShouldBe(0, "local backpressure must not retire a healthy route");
+ fixture.Opens.ShouldBe(1, "nor force a re-snapshot");
+ foreach (var demand in demands) demand.IsValid.ShouldBeTrue();
+ }
+ finally { foreach (var demand in demands) demand.Dispose(); }
+ }
+
+ // R-2 (found by the 10k perf harness): the origin session's delivery index was sized from its frame window
+ // (MaxPendingFrames × 16 = 1024), so the 1025th item of one stream stopped the session after its acknowledgement and
+ // a cohort above 1024 items could never open.
+ [Fact(Timeout = 120000), Trait("Issue", "994")]
+ public async Task R2_a_cohort_above_1024_items_opens_on_one_origin_stream()
+ {
+ using var fixture = new CohortScaleFixture(1100, maxBatchItems: 1000);
+ using var access = fixture.Create(2048);
+ var demands = fixture.AcquireAll(access);
+ try
+ {
+ foreach (var demand in demands) access.StartSubscription(demand, TimeSpan.FromSeconds(1)).ShouldBeTrue();
+ await fixture.WaitForAsync(() => fixture.Baselines.Count == 1100, TimeSpan.FromSeconds(60),
+ $"every item must reach its first value; baselines={fixture.Baselines.Count} opens={fixture.Opens}");
+ fixture.Opens.ShouldBe(1);
+ }
+ finally { foreach (var demand in demands) demand.Dispose(); }
+ }
+}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs
index 53ac4fd95..3d28aea73 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs
@@ -589,6 +589,50 @@ public sealed class GrpcDataConnectionClientTests
result[1].Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
second.WrittenIds.ShouldBe(new[] { "retry" });
}
+ // #994 (R-8): a per-call failure after a successful endpoint selection used to arm the connection-wide discovery backoff,
+ // refusing every other operation on the connection ("Data endpoint discovery is backing off") for ~250 ms+.
+ [Fact, Trait("Issue", "994")]
+ public async Task R8_a_per_call_failure_after_selection_does_not_back_off_the_connection()
+ {
+ var calls = 0;
+ var only = new FailoverHandler("a", false, onMetadata: () => { if (Interlocked.Increment(ref calls) == 1) throw new HttpRequestException("one bad call"); });
+ using var manager = new DataConnectionManager("consumer", 1);
+ manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } });
+ await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
+ [new Uri("https://a.test")], new PairSecurity(only, only), manager.Acquire("link"), 65536, 1, new ManualTimeProvider());
+ await Should.ThrowAsync(() => connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken));
+ // The very next call (same instant on the manual clock) reaches the endpoint instead of being refused unsent.
+ (await connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken)).ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Good);
+ calls.ShouldBe(2);
+ }
+
+ [Fact, Trait("Issue", "994")]
+ public async Task R8_a_caller_cancel_surfaces_as_cancellation_and_does_not_back_off_the_connection()
+ {
+ using var cancel = new CancellationTokenSource();
+ var calls = 0;
+ var only = new FailoverHandler("a", false, onMetadata: () => { if (Interlocked.Increment(ref calls) == 1) { cancel.Cancel(); throw new OperationCanceledException(cancel.Token); } });
+ using var manager = new DataConnectionManager("consumer", 1);
+ manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } });
+ await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
+ [new Uri("https://a.test")], new PairSecurity(only, only), manager.Acquire("link"), 65536, 1, new ManualTimeProvider());
+ await Should.ThrowAsync(() => connection.GetMetadataAsync(new([View], Budget), cancel.Token));
+ (await connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken)).ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Good);
+ }
+
+ [Fact, Trait("Issue", "994")]
+ public async Task R8_positive_control_an_unselectable_endpoint_still_backs_off()
+ {
+ var only = new FailoverHandler("a", false, unavailable: true);
+ using var manager = new DataConnectionManager("consumer", 1);
+ manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } });
+ await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
+ [new Uri("https://a.test")], new PairSecurity(only, only), manager.Acquire("link"), 65536, 1, new ManualTimeProvider());
+ await Should.ThrowAsync(() => connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken));
+ (await Should.ThrowAsync(() => connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken)))
+ .Message.ShouldContain("backing off");
+ }
+
private sealed class PairSecurity(FailoverHandler first, FailoverHandler second) : IDataConnectionSecurityProvider
{
public event Action? Changed { add { } remove { } }
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataInterestScalingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataInterestScalingTests.cs
new file mode 100644
index 000000000..d9f55daff
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataInterestScalingTests.cs
@@ -0,0 +1,98 @@
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
+
+namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
+
+/// #994: interest leases under unrelated partition traffic (review 2026-12-02 R-3, R-9).
+[Trait("Feature", "GrpcData")]
+[Trait("Category", "Unit")]
+public sealed class GrpcDataInterestScalingTests
+{
+ // HubTest keeps ONE history entry per partition, so any two unrelated changes between reads roll the cursor off it —
+ // the shape a busy node produces with the production 1024-entry history and thousands of changes per second.
+ [Fact, Trait("Issue", "994")]
+ public void R3_unrelated_traffic_that_rolls_the_history_off_does_not_reset_the_lease_and_own_changes_still_arrive()
+ {
+ using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100);
+ var mine = HubTest.Ticket("driver", "mine");
+ var other = HubTest.Ticket("driver", "busy");
+ HubTest.BindAndPublish(hub, mine, 1, 1);
+ HubTest.BindAndPublish(hub, other, 1, 1);
+ hub.ProcessPending();
+ hub.TryCaptureInterestSnapshot([mine], HubTest.Budget, CancellationToken.None, out var snapshot, out var interest).ShouldBeTrue();
+ using (interest!)
+ {
+ snapshot!.Dispose();
+ for (var version = 2; version <= 5000; version++) { HubTest.Publish(hub, other, version, version); hub.ProcessPending(); }
+ interest!.TryReadChanges(32, out var changes).ShouldBeTrue("unrelated traffic is not this lease's reset");
+ changes.ShouldBeEmpty();
+ // Positive control: this lease's own source still reports, after the catch-up.
+ HubTest.Publish(hub, mine, 2, 2); HubTest.Publish(hub, other, 5001, 1); hub.ProcessPending();
+ interest.TryReadChanges(32, out changes).ShouldBeTrue();
+ changes.ShouldHaveSingleItem().Ticket.ShouldBe(mine);
+ }
+ }
+
+ [Fact, Trait("Issue", "994")]
+ public void R3_a_lease_behind_its_scan_budget_reports_more_and_its_own_changes_are_not_starved()
+ {
+ using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100);
+ var mine = HubTest.Ticket("driver", "mine");
+ var other = HubTest.Ticket("driver", "busy");
+ HubTest.BindAndPublish(hub, mine, 1, 1);
+ HubTest.BindAndPublish(hub, other, 1, 1);
+ hub.ProcessPending();
+ hub.TryCaptureInterestSnapshot([mine], HubTest.Budget, CancellationToken.None, out var snapshot, out var interest).ShouldBeTrue();
+ using (interest!)
+ {
+ snapshot!.Dispose();
+ HubTest.Publish(hub, mine, 2, 2); hub.ProcessPending();
+ interest!.TryReadChanges(256, 4096, out var changes, out var more).ShouldBeTrue();
+ changes.ShouldHaveSingleItem().Ticket.ShouldBe(mine); more.ShouldBeFalse();
+ }
+ }
+
+ [Fact, Trait("Issue", "994")]
+ public void R9_invalidating_one_source_does_not_reset_a_lease_on_a_sibling_source_of_the_same_partition()
+ {
+ using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100);
+ var first = HubTest.Ticket("driver", "first");
+ var second = HubTest.Ticket("driver", "second");
+ HubTest.BindAndPublish(hub, first, 1, 1);
+ HubTest.BindAndPublish(hub, second, 1, 1);
+ hub.ProcessPending();
+ hub.TryCaptureInterestSnapshot([first], HubTest.Budget, CancellationToken.None, out var firstSnapshot, out var firstInterest).ShouldBeTrue();
+ hub.TryCaptureInterestSnapshot([second], HubTest.Budget, CancellationToken.None, out var secondSnapshot, out var secondInterest).ShouldBeTrue();
+ using (firstInterest!) using (secondInterest!)
+ {
+ firstSnapshot!.Dispose(); secondSnapshot!.Dispose();
+ hub.Invalidate(first, "source serialization contention");
+ secondInterest!.IsReset.ShouldBeFalse("a sibling's invalidation is not this lease's");
+ secondInterest.TryReadChanges(32, out _).ShouldBeTrue();
+ // Positive control: the invalidated source's own lease still resets.
+ (firstInterest!.IsReset || !firstInterest.TryReadChanges(32, out _)).ShouldBeTrue();
+ // ...and the sibling lease keeps delivering afterwards.
+ HubTest.Publish(hub, second, 2, 2); hub.ProcessPending();
+ secondInterest.TryReadChanges(32, out var changes).ShouldBeTrue();
+ changes.ShouldContain(change => change.Ticket == second);
+ }
+ }
+
+ [Fact, Trait("Issue", "994")]
+ public void R9_a_partition_wide_invalidation_still_resets_every_lease()
+ {
+ using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100);
+ var first = HubTest.Ticket("driver", "first");
+ HubTest.BindAndPublish(hub, first, 1, 1);
+ hub.ProcessPending();
+ hub.TryCaptureInterestSnapshot([first], HubTest.Budget, CancellationToken.None, out var snapshot, out var interest).ShouldBeTrue();
+ using (interest!)
+ {
+ snapshot!.Dispose();
+ hub.InvalidatePartitionFor(first.Key, "partition overflow");
+ hub.ProcessPending();
+ (interest!.IsReset || !interest.TryReadChanges(32, out _)).ShouldBeTrue();
+ }
+ }
+}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs
index 76f25b4b3..13f9f08f6 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs
@@ -278,12 +278,13 @@ internal sealed class LocalDataFixture : IDisposable
Func? writes = null, bool denyReadExport = false,
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1",
IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100,
- string? siblingPattern = null, bool unsOnlyExport = false)
+ string? siblingPattern = null, bool unsOnlyExport = false, int maxMonitoredItems = 100, int maxMessageBytes = 1_000_000,
+ bool subscriptionFreshnessChallenges = false, long hubBytes = 1_000_000)
{
if (clock is not null) Clock = clock;
Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration };
Ticket = new(SourceKey.ForDriver("cluster", "driver", "Plant/Driver/Device/Speed", servingNode, servingIncarnation), new(1, 1));
- Hub = HubTest.Create(clock: Clock, bytes: 1_000_000);
+ Hub = HubTest.Create(clock: Clock, bytes: hubBytes);
Hub.TryBind(Ticket).ShouldBeTrue();
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
Authority.Apply("cluster", "first", [key],
@@ -348,11 +349,12 @@ internal sealed class LocalDataFixture : IDisposable
unsOnlyExport ? [new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }] :
[new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations },
new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]);
- var limits = new DataLimits(100, maxBatchItems, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
+ var limits = new DataLimits(100, maxBatchItems, maxMessageBytes, maxMonitoredItems, 10, maxMessageBytes, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits);
Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority,
new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, writes: writes, subscriptions: subscriptions,
- targetSubscriptions: targetSubscriptions, history: history) { HistoryDiagnostics = HistoryDiagnostics };
+ targetSubscriptions: targetSubscriptions, history: history,
+ subscriptionFreshnessChallenges: subscriptionFreshnessChallenges) { HistoryDiagnostics = HistoryDiagnostics };
}
internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", Serving.NodeId));
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs
index 8bf0de468..a043c0614 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs
@@ -514,10 +514,10 @@ public sealed partial class GrpcDataProjectedAccessTests
fixture.StreamOpens.ShouldBe(1, "refreshing one registration must not restart its healthy cohort");
fixture.StreamClosed.Task.IsCompleted.ShouldBeFalse();
var commands = fixture.StreamCommands.ToArray();
- var initial = commands.OfType().Single().Items.Single();
- var other = commands.OfType().First().Items.Single();
+ var initial = fixture.ItemFor(fixture.Proof.OriginMetadata.View);
+ var other = fixture.ItemFor(fixture.SecondProof!.OriginMetadata.View);
var removed = commands.OfType().Single();
- var rebound = commands.OfType().Last().Items.Single();
+ var rebound = fixture.ItemFor(fixture.Proof.OriginMetadata.View, nth: 1);
rebound.View.ShouldBe(initial.View);
rebound.ClientItemId.ShouldNotBe(initial.ClientItemId);
removed.Items.ShouldHaveSingleItem().ShouldBe(fixture.StreamHandles[initial.ClientItemId]);
@@ -594,7 +594,7 @@ public sealed partial class GrpcDataProjectedAccessTests
access.StartSubscription(healthy!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await fixture.ReadUpdateAsync(); await fixture.ReadUpdateAsync();
- var healthyId = fixture.StreamCommands.OfType().Single().Items.Single().ClientItemId;
+ var healthyId = fixture.ItemFor(fixture.SecondProof!.OriginMetadata.View).ClientItemId;
fixture.HoldNextSnapshotEnd = true;
access.RequestFreshSnapshot(slow!).ShouldBeTrue();
await fixture.SnapshotEndHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
@@ -624,7 +624,7 @@ public sealed partial class GrpcDataProjectedAccessTests
new[] { one.Route.LocalIdentifier, two.Route.LocalIdentifier }.ShouldBe(new[] { fixture.Proof.LocalIdentifier, fixture.SecondProof!.LocalIdentifier }, ignoreOrder: true);
one.Route.PublicationId.ShouldNotBe(two.Route.PublicationId);
fixture.StreamOpens.ShouldBe(1);
- var other = fixture.StreamCommands.OfType().Single().Items.Single();
+ var other = fixture.SentItems()[1]; // aliases: one origin view, so the second item sent is the second demand's
await access.DisposeConfiguredAsync(first);
var surviving = one.Route.LocalIdentifier == fixture.SecondProof.LocalIdentifier ? one : two;
surviving.SourceProof.IsValid.ShouldBeTrue();
@@ -810,7 +810,7 @@ public sealed partial class GrpcDataProjectedAccessTests
access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
access.StartSubscription(healthy!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
- var other = fixture.StreamCommands.OfType().Single().Items.Single();
+ var other = fixture.ItemFor(fixture.SecondProof!.OriginMetadata.View);
access.RequestFreshSnapshot(slow!).ShouldBeTrue();
await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
slow!.Dispose();
@@ -819,7 +819,7 @@ public sealed partial class GrpcDataProjectedAccessTests
fixture.ReleaseRemoveAck();
fixture.EmitValue(other.ClientItemId, 3, 43);
(await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(43);
- fixture.StreamCommands.OfType().Count().ShouldBe(1);
+ fixture.SentItems().Length.ShouldBe(2, "the withdrawn registration is never re-added");
fixture.StreamOpens.ShouldBe(1); healthy!.IsValid.ShouldBeTrue();
slow.IsValid.ShouldBeFalse();
}
@@ -922,6 +922,13 @@ public sealed partial class GrpcDataProjectedAccessTests
internal readonly TaskCompletionSource SnapshotEndHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal async Task ReadUpdateAsync() => await Updates.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
internal readonly System.Collections.Concurrent.ConcurrentQueue StreamCommands = new();
+ // #994 (R-2): a cohort batches its open/add commands, so which command carries which demand depends on scheduling;
+ // tests find a demand's item by its origin view (then by send order among items of one view).
+ internal DataSubscriptionItem[] SentItems(TimeSpan? interval = null) => StreamCommands.SelectMany(command => command switch
+ { OpenSubscription open => open.Items, AddSubscriptionItems add => add.Items, _ => (IEnumerable)[] })
+ .Where(item => interval is null || item.Settings.PublishingInterval == interval).ToArray();
+ internal DataSubscriptionItem ItemFor(DataView originView, int nth = 0, TimeSpan? interval = null) =>
+ SentItems(interval).Where(item => item.View == originView).ElementAt(nth);
internal readonly System.Collections.Concurrent.ConcurrentDictionary StreamHandles = new();
private readonly System.Collections.Concurrent.ConcurrentQueue _streamsByOwner = new();
internal bool BlockStreamDispose;
@@ -1104,19 +1111,23 @@ public sealed partial class GrpcDataProjectedAccessTests
var total = Interlocked.Add(ref owner._totalStreamItems, items.Count);
if (total >= 2) owner.SecondTotalStreamItem.TrySetResult(); if (total >= 3) owner.ThirdStreamItem.TrySetResult();
_frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));
- if (owner._array && acks.Length > 0)
+ // #994 (R-2): one snapshot covers every item of the (now batched) command, as the origin's does.
+ foreach (var ack in acks)
{
- var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast