fix(grpc-data): #994 projected cohorts batch, pace and scale past one item; busy origins no longer reset quiet streams

Wave 3 of the 2026-12-02 review (docs/reviews/2026-12-02/01-runtime.md R-2/3/7/8/9/10/12/13/21/22/23/24,
02-opcuaserver.md U-10/11/12/13).

Consumer (ProjectedDataAccess cohort):
- R-2: a cohort's OpenSubscription declared a snapshot budget of 1 item, which the origin uses to size the stream's
  handle table, so the 2nd item was refused LimitExceeded and the cohort re-opened in a loop (two projected items of
  one interval broke each other). Opens/adds/removes are now batched (IDataSubscriptionCommandLimits, <=256 items,
  bounded by estimated snapshot bytes) and paced (32 burst, 32/s, <=4 commands or snapshots outstanding).
- R-7: control events no longer share the bounded frame queue; a failed Remove can no longer Stop() the cohort.
- R-10: a local capacity refusal (TryPublishOrBackpressure -> CapacityExhausted) is retried for up to 2 s instead of
  invalidating healthy evidence and retiring the route.
- R-13: RemoteSubscription mutates its handle/version tables in place; the cohort caches the source per binding and
  drops the per-sample LINQ in EvidenceFor.
- R-8: only an unselectable endpoint arms the discovery backoff; a caller cancel is OperationCanceledException.
- R-24: the condition stream cancels and observes a pending frame read before disposing the enumerator.

Origin (DataSubscriptionSession / SamplePartition / SourceInterestLease):
- R-2 (found by the perf harness): the delivery index was sized MaxPendingFrames x 16 = 1024, so the 1025th item of a
  stream stopped the session after its ack; it now covers MaxMonitoredItems.
- R-3: interest reads count only own-ticket matches (scan budget separate), re-queue a lagging tick, and catch up from
  per-source last-change versions when the bounded history rolled off - no more "Source change history expired".
- R-9: a partition quiet bump resets a lease only when one of ITS sources was invalidated (per-source quiet version)
  or its binding retired; partition-wide invalidation still resets all.
- R-12: the per-item publish verdict is memoised per (catalog instance, authority generation) for <=1 s; Commit
  under the session lock re-checks identity only.
- R-21/R-22/R-23: registry prune is interval/capacity driven; a cleared history session refuses chunks; the snapshot
  barrier is decided and armed under the same gate its release is decided under.

Node manager: U-10 projected live items indexed by node; U-11 anchor removal / root-leaf swap tombstone the anchor's
own monitored node; U-12 per-parent child count; U-13 per-condition verdict index.

Also: Issue934_r1_N1 test clears its metadata failure before ending the stream (test-only sequencing race,
reproduced with a 200 ms delay; production behaviour correct).

Perf (Category=Perf, OTOPCUA_GRPCDATA_PERF=1): 10k-item cohort opens in 3.3 s / 80 commands / 1 stream (before: never
opens); 100 source versions at 1k/s -> 11,036 item values in 569 ms.
This commit is contained in:
Joseph Doherty
2026-12-03 11:59:26 -05:00
parent b9955f6946
commit 5cccfd75ce
30 changed files with 1697 additions and 189 deletions
+47
View File
@@ -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`)
@@ -149,6 +149,16 @@ public interface IDataSubscriptionFreshnessSupport
int FreshnessMaxItems { get; }
}
/// <summary>
/// #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).
/// </summary>
public interface IDataSubscriptionCommandLimits
{
int MaxCommandItems { get; }
}
/// <summary>
/// A3 (review r1, deviation 9): a connection that can open a subscription served by the origin's <b>Primary</b> 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.
@@ -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<ProjectedMonitoredItem>()) 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<ProjectedMonitoredItem>())
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<NodeId, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard)> _projectedVariables = new();
private readonly ProjectedVariableTable _projectedVariables = new();
/// <summary>
/// #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 <c>Values.Any(child => child.Parent == id)</c> scan per candidate (O(N²) per reservation at the node cap).
/// Writers hold Lock (as for the plain dictionary it replaces).
/// </summary>
private sealed class ProjectedVariableTable
{
private readonly Dictionary<NodeId, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard)> _entries = new();
private readonly Dictionary<NodeId, int> _children = new();
internal int Count => _entries.Count;
internal Dictionary<NodeId, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> 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<bool> Guard) entry) =>
_entries.TryGetValue(id, out entry);
internal (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> 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<bool> 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<bool> 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<bool> 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
/// </remarks>
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.
/// </remarks>
private readonly ConcurrentDictionary<ISampledDataChangeMonitoredItem, LiveItem> _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<NodeId, HashSet<ProjectedMonitoredItem>> _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<ProjectedMonitoredItem> _projectedHealthItems = new();
private readonly Dictionary<ProjectedMonitoredItem, LinkedListNode<ProjectedMonitoredItem>> _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);
@@ -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();
/// <summary>#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.</summary>
private readonly Dictionary<NodeId, HashSet<object>> _verdictIdentities = new();
internal int VerdictCountForTests { get { lock (_verdictGate) return _verdicts.Count; } }
public int Count => _byNode.Count;
public IEnumerable<ImportedCondition> 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;
}
@@ -190,10 +190,15 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
NotifyRetirements();
}
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates)
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates) => Publish(updates, backpressure: false) == ProjectedPublishOutcome.Accepted;
/// <inheritdoc />
public ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList<ProjectedValueUpdate> updates) => Publish(updates, backpressure: true);
private ProjectedPublishOutcome Publish(IReadOnlyList<ProjectedValueUpdate> 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; } }
}
@@ -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
{
/// <summary>#994 (R-2): the peer's batch limit, within the connection row's batch and monitored-item caps.</summary>
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;
@@ -5,8 +5,10 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>One caller-bound subscription with bounded commands and one ordered delivery mode.</summary>
internal sealed partial class DataSubscriptionSession : IDataSubscriptionTransport
internal sealed partial class DataSubscriptionSession : IDataSubscriptionTransport, IDataSubscriptionCommandLimits
{
/// <summary>#994 (R-2): one command may carry up to the origin's batch limit.</summary>
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<PendingDelivery>(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;
@@ -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<ReadResult> 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<W.SubscriptionCommand, W.SubscriptionFrame> call, Selected selected,
CancellationTokenSource lifetime, bool compactNegotiated, int maxBytes, int maxItems, int maxPendingCommands,
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func<string, long, bool> claimEpoch, Action<WeakReference>? observePending,
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance, IDataSubscriptionFreshnessSupport
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance, IDataSubscriptionFreshnessSupport,
IDataSubscriptionCommandLimits
{
public ServingIdentity Serving { get; } = selected.Capabilities.Serving;
/// <summary>#994 (R-2): the origin's advertised batch limit, within this stream's own item cap.</summary>
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<string, long> _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<ulong, DataItemHandle>(_handles);
var nextClients = new Dictionary<string, ulong>(_clientHandles, StringComparer.Ordinal);
var nextUsed = new HashSet<ulong>(_usedHandles);
var nextVersions = new Dictionary<ulong, long>(_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<ulong, long>(_versions);
var seen = new HashSet<ulong>();
// #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<ulong>? seen = values.Items.Count > 1 ? new HashSet<ulong>(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<DataSubscriptionValue>(values.Items.Count);
@@ -45,8 +45,18 @@ public interface IProjectedValuePublisher
bool TryBind(ProjectedValueRoute route);
bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates);
void Retire(ProjectedValueRoute route);
/// <summary>
/// #994 (R-10): like <see cref="TryPublish"/>, but a refusal for lack of local capacity (pending bytes) answers
/// <see cref="ProjectedPublishOutcome.CapacityExhausted"/> 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.
/// </summary>
ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList<ProjectedValueUpdate> updates) =>
TryPublish(updates) ? ProjectedPublishOutcome.Accepted : ProjectedPublishOutcome.Refused;
}
/// <summary>#994 (R-10): the outcome of a projected publication.</summary>
public enum ProjectedPublishOutcome { Accepted, Refused, CapacityExhausted }
/// <summary>A driver facade over a configured, scoped data connection.</summary>
public sealed class GrpcDataDriverAdapter : IDriver, IBatchSubscribable, IWriteOutcomeCapability
{
@@ -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;
}
/// <summary>#994 (R-12): how long a memoised per-item publish verdict may be reused for the same catalog + authority.</summary>
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)
@@ -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);
}
@@ -294,6 +294,7 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
var controls = new Dictionary<int, long>();
var quietControls = new Dictionary<int, long>();
var owners = new Dictionary<SourceTicket, (SamplePartition Partition, object Source)>();
var quietVersions = new Dictionary<SourceTicket, long>();
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;
@@ -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<DataSubscriptionFrame>? frames = null;
Task<bool>? 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<bool>? 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
}
}
}
/// <summary>
/// #994 (R-24): ends a frame loop that may have a <c>MoveNextAsync</c> 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.
/// </summary>
internal static class ProjectedStreamTeardown
{
internal static async Task StopAsync<T>(CancellationTokenSource stop, Task<bool>? pending, IAsyncEnumerator<T>? 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) { } }
}
}
@@ -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;
/// <summary>#994 (R-2): the command pacer has a slot again; flush the queued adds/removes/challenges.</summary>
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<Event> _events;
private readonly SemaphoreSlim _frameSlots;
private readonly CancellationTokenSource _stop = new();
private readonly Dictionary<Demand, Registration> _registrations = new();
private readonly Dictionary<string, Registration> _byId = new(StringComparer.Ordinal);
private readonly Dictionary<DataItemHandle, Registration> _byHandle = new();
private readonly Dictionary<string, Registration> _removing = new(StringComparer.Ordinal);
private readonly Dictionary<string, List<Registration>> _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;
/// <summary>
/// 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.
/// </summary>
internal const int MaxOutstandingCommands = 4;
/// <summary>Items per command when the stream does not advertise its peer's batch limit.</summary>
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<Demand> _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<Event>(new BoundedChannelOptions(Math.Clamp(owner._limits.MaxDemands * 2, 4, 128))
{ SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
_events = Channel.CreateUnbounded<Event>(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()); }
}
/// <summary>#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.</summary>
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)));
}
/// <summary>
/// #994 (R-2): how many queued registrations fit one add command: at most <paramref name="commandItems"/>, 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 <paramref name="maxBytes"/>) stay within half of <paramref name="maxBytes"/>.
/// </summary>
private static int AddBatchSize(List<Registration> 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<Demand, SourceState>();
var renewals = new Dictionary<Demand, Task>();
var renewalQueued = 0;
var pendingCommands = new Dictionary<string, Registration>();
var pendingCommands = new Dictionary<string, List<Registration>>(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<Registration>();
var removeQueue = new List<Registration>();
ITimer? flushTimer = null;
var commandItems = DefaultCommandItems;
var snapshotQueue = new Queue<HashSet<Registration>>();
HashSet<Registration>? snapshotOwners = null;
void EnqueueSnapshot(HashSet<Registration> 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<Registration>();
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)
{
@@ -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<SourceTicket> tickets, Dictionary<SourceTicket, SnapshotItem> items,
Dictionary<SourceTicket, object> interests, out long watermark, out long epoch,
Dictionary<SourceTicket, object> interests, Dictionary<SourceTicket, long> 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);
/// <summary>#994 (R-9): the source's quiet version (see <see cref="SourceState.QuietVersion"/>); lock-free.</summary>
internal static long QuietVersionOf(object source) => Interlocked.Read(ref ((SourceState)source).QuietVersion);
internal bool ReadInterestChanges(long epoch, ref long position, IReadOnlyDictionary<BackingSourceKey, SourceTicket> tickets,
int maximum, List<SourceInterestChange> changes, out int scanned)
int maximum, List<SourceInterestChange> changes, out int scanned) =>
ReadInterestChanges(epoch, ref position, tickets, maximum, int.MaxValue, changes, out scanned, out _);
/// <summary>
/// #994 (R-3): reads this lease's changes since <paramref name="position"/>. At most <paramref name="maximumMatches"/>
/// changes of ITS OWN tickets are returned and at most <paramref name="maximumScanned"/> partition entries walked
/// (unrelated traffic no longer consumes the match budget); <paramref name="more"/> 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 <see cref="SourceState.LastChange"/> — O(own tickets) — instead of resetting the stream.
/// </summary>
internal bool ReadInterestChanges(long epoch, ref long position, IReadOnlyDictionary<BackingSourceKey, SourceTicket> tickets,
int maximumMatches, int maximumScanned, List<SourceInterestChange> 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;
/// <summary>#994 (R-3): the partition watermark of this source's latest recorded change (under the partition gate).</summary>
public long LastChange;
/// <summary>
/// #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.
/// </summary>
public long QuietVersion;
}
private sealed class Pending
{
@@ -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<BackingSourceKey, SourceTicket> Tickets = tickets;
}
private readonly object _gate = new();
private readonly PartitionedSampleHub _hub;
private readonly Dictionary<SourceTicket, (SamplePartition Partition, object Source)> _owners;
private readonly Dictionary<SourceTicket, long> _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<SourceTicket, (SamplePartition Partition, object Source)> owners,
IReadOnlyDictionary<int, long> watermarks, IReadOnlyDictionary<int, long> epochs, IReadOnlyDictionary<int, long> quietControls,
long routingEpoch, long charge, CancellationToken cancellationToken)
Dictionary<SourceTicket, long> 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(); }
}
/// <summary>
/// #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.
/// </summary>
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;
}
/// <summary>Scans at most maximum retained partition changes, returning false on a gap or epoch reset.</summary>
public bool TryReadChanges(int maximum, out IReadOnlyList<SourceInterestChange> changes)
public bool TryReadChanges(int maximum, out IReadOnlyList<SourceInterestChange> changes) =>
TryReadChanges(maximum, maximum, out changes, out _);
/// <summary>
/// #994 (R-3): returns at most <paramref name="maximumMatches"/> changes of this lease's own sources, walking at most
/// <paramref name="maximumScanned"/> partition entries; <paramref name="more"/> is true when a cursor is still behind
/// (the caller re-queues instead of waiting for its next timer tick).
/// </summary>
public bool TryReadChanges(int maximumMatches, int maximumScanned, out IReadOnlyList<SourceInterestChange> 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<SourceInterestChange>();
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);
@@ -20,6 +20,7 @@ public sealed class WriteOperationRegistry
private readonly TimeSpan _retention;
private readonly TimeProvider _clock;
private long _retainedBytes;
private long _lastPrune;
/// <param name="maxEntriesPerPrincipal">
/// A2b security review: the most entries one principal may hold at once (null ⇒ <paramref name="maxEntries"/>, 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);
@@ -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<FolderState>();
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<IAsyncNodeManager, InertProxy>();
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
{
@@ -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()
{
@@ -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;
/// <summary>
/// #994 (R-2/R-7/R-13): a consumer <see cref="ProjectedDataAccess"/> holding <c>N</c> projected demands, every one
/// subscribed through ONE cohort onto a REAL origin <see cref="DataSubscriptionSession"/> (real
/// <see cref="SubscriptionTransportCapacity"/>, 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.
/// </summary>
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<NodeId, ProjectedVariableDefinition> _definitions = new();
private readonly Dictionary<string, ProjectedNodeProof> _proofs = new(StringComparer.Ordinal);
internal readonly ConcurrentDictionary<string, int> Baselines = new(StringComparer.Ordinal);
internal readonly ConcurrentDictionary<string, long> Latest = new(StringComparer.Ordinal);
internal int Retired, Publishes, Opens;
/// <summary>When set, TryPublish answers false (a capacity-refusing sink).</summary>
#pragma warning disable CS0649 // set by individual tests
internal volatile bool RefusePublish;
internal Func<ProjectedValueUpdate, bool>? PublishGate;
#pragma warning restore CS0649
internal readonly ConcurrentQueue<DataSubscriptionCommand> Commands = new();
private readonly ConcurrentQueue<IDataSubscription> _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<bool> 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
};
/// <summary>
/// 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.
/// </summary>
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();
}
/// <summary>Drops the current physical stream (origin restart / failover) so the cohort must re-open everything.</summary>
internal async Task DropStreamAsync()
{
foreach (var stream in _streams.ToArray()) await stream.DisposeAsync();
}
public TimeProvider Clock => Origin.Clock;
public event Action<string, long>? Invalidated { add { } remove { } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => throw new NotSupportedException();
public Task<IProjectedPreparedPage> 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<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(Origin.Connection()));
public bool TryBind(ProjectedValueRoute route) => true;
/// <summary>#994 (R-10): this many publications are answered CapacityExhausted (a momentarily full sink).</summary>
internal int CapacityRefusals;
public ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList<ProjectedValueUpdate> 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<ProjectedValueUpdate> 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<IDataSubscription> 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<string, long> _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<DataSubscriptionFrame> 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<DataSubscriptionValue>(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();
}
}
@@ -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;
/// <summary>#994: projected-cohort scaling against a real origin session (review 2026-12-02 R-2, R-7, R-13).</summary>
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(); }
}
}
@@ -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<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "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<InvalidOperationException>(() => 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<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "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<OperationCanceledException>(() => 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<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "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<InvalidOperationException>(() => connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken));
(await Should.ThrowAsync<InvalidOperationException>(() => connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken)))
.Message.ShouldContain("backing off");
}
private sealed class PairSecurity(FailoverHandler first, FailoverHandler second) : IDataConnectionSecurityProvider
{
public event Action<string>? Changed { add { } remove { } }
@@ -0,0 +1,98 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>#994: interest leases under unrelated partition traffic (review 2026-12-02 R-3, R-9).</summary>
[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();
}
}
}
@@ -278,12 +278,13 @@ internal sealed class LocalDataFixture : IDisposable
Func<DataAuthenticatedContext, IDataWriteService>? 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));
@@ -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<OpenSubscription>().Single().Items.Single();
var other = commands.OfType<AddSubscriptionItems>().First().Items.Single();
var initial = fixture.ItemFor(fixture.Proof.OriginMetadata.View);
var other = fixture.ItemFor(fixture.SecondProof!.OriginMetadata.View);
var removed = commands.OfType<RemoveSubscriptionItems>().Single();
var rebound = commands.OfType<AddSubscriptionItems>().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<AddSubscriptionItems>().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<AddSubscriptionItems>().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<AddSubscriptionItems>().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<AddSubscriptionItems>().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<ProjectedValueUpdate> ReadUpdateAsync() => await Updates.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
internal readonly System.Collections.Concurrent.ConcurrentQueue<DataSubscriptionCommand> 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<DataSubscriptionItem>)[] })
.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<string, DataItemHandle> StreamHandles = new();
private readonly System.Collections.Concurrent.ConcurrentQueue<TestStream> _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<object>().ToArray(), [owner.ReadElements.Length]);
var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), serving, 1);
_frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true,
[new DataSubscriptionValue(acks[0].Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)]));
}
if (owner.ScalarSnapshots && acks.Length > 0)
{
var sample = new DataSample(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, 7), 0, null, owner.Clock.GetUtcNow(), serving, 1);
_frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true,
[new DataSubscriptionValue(acks[0].Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready,
FreshnessObservedTimestamp: owner.SnapshotObservedTimestamp)]));
if (owner._array)
{
var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast<object>().ToArray(), [owner.ReadElements.Length]);
var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), serving, 1);
_frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true,
[new DataSubscriptionValue(ack.Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)]));
}
if (owner.ScalarSnapshots)
{
var sample = new DataSample(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, 7), 0, null, owner.Clock.GetUtcNow(), serving, 1);
_frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true,
[new DataSubscriptionValue(ack.Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready,
FreshnessObservedTimestamp: owner.SnapshotObservedTimestamp)]));
}
}
if (owner.HoldNextSnapshotEnd)
{
@@ -1286,10 +1286,13 @@ public sealed class GrpcDataProjectedConditionAccessTests
stream.Complete("map-b");
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) == 2); // the re-resolve is in flight
f.Connections.MetadataCancelled.ShouldBe(0);
// #994: make map-a resolvable BEFORE ending the stream. The in-flight re-resolve is already blocked (it can no longer
// see this set), and the reconnect re-resolves 50 ms after the end — clearing it after the end raced that reconnect
// whenever this thread was slow (a loaded full-suite run), so the next stream opened without map-a.
f.Connections.MetadataFails.Clear();
stream.End(); // a natural end (no consumer cancellation)
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCancelled) == 1);
f.Connections.MetadataFails.Clear();
var next = await f.NextStreamAsync(); // positive control: the next stream resolves map-a at its open
next.Mappings.ShouldBe(["map-a", "map-b"]);
stream.AddsOf("map-a").ShouldBe(0, "the abandoned answer was never applied");
@@ -78,9 +78,8 @@ public sealed partial class GrpcDataProjectedAccessTests
access.StartSubscription(second!, TimeSpan.FromSeconds(2)).ShouldBeTrue();
access.StartSubscription(otherSource!, TimeSpan.FromSeconds(2)).ShouldBeTrue();
await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var secondId = fixture.StreamCommands.OfType<OpenSubscription>().Single(x =>
x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items[0].ClientItemId;
var otherId = fixture.StreamCommands.OfType<AddSubscriptionItems>().Single().Items[0].ClientItemId;
var secondId = fixture.ItemFor(fixture.Proof.OriginMetadata.View, interval: TimeSpan.FromSeconds(2)).ClientItemId;
var otherId = fixture.ItemFor(fixture.SecondProof!.OriginMetadata.View, interval: TimeSpan.FromSeconds(2)).ClientItemId;
fixture.EmitValue(secondId, 2, 8);
ProjectedValueUpdate observed;
do { observed = await fixture.ReadUpdateAsync(); } while (!Equals(observed.Snapshot.Value, 8));
@@ -0,0 +1,54 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>#994 (R-10): a full local publication budget is backpressure, not invalid evidence.</summary>
[Trait("Feature", "GrpcData"), Trait("Issue", "994")]
public sealed class GrpcDataPublisherBackpressureTests : RuntimeActorTestBase
{
private static ProjectedValueRoute Route(string node)
{
var id = ProjectedDataIds.Identifier("mapping", new DataAddress("cluster", "urn:raw", "string", node));
return new("grpc-data:link", ProjectedDataIds.DependencyReference(DataRealm.Raw, id), DataRealm.Raw, id, 1,
new ServingIdentity("node", "boot", "Primary", 1, 1, 1), Guid.NewGuid());
}
[Fact]
public void A_capacity_refusal_keeps_the_proof_and_the_route_and_the_legacy_path_still_fails_closed()
{
var clock = new ManualTimeProvider();
var actor = CreateTestProbe(); // never drains: the first publication stays pending
using var publisher = new ActorProjectedValuePublisher(() => actor.Ref, _ => true, 4, 1_500, clock); // one ~800-byte charge fits, two do not
var first = Route("first"); var second = Route("second");
publisher.TryBind(first).ShouldBeTrue(); publisher.TryBind(second).ShouldBeTrue();
ProjectedValueUpdate Update(ProjectedValueRoute route, TestProof proof) => new(route, new DataValueSnapshot(7, 0, null, null),
new(TimeSpan.Zero, TimeSpan.Zero), clock.GetTimestamp(), proof, true, TimeSpan.FromSeconds(1), 1);
publisher.TryPublish([Update(first, new TestProof(clock))]).ShouldBeTrue();
var healthy = new TestProof(clock);
publisher.TryPublishOrBackpressure([Update(second, healthy)]).ShouldBe(ProjectedPublishOutcome.CapacityExhausted);
healthy.Invalidations.ShouldBe(0, "full is not invalid");
publisher.IsCurrent(second).ShouldBeTrue("the route is not retired by local backpressure");
// Positive control: the legacy boolean path (reads, the driver adapter) still refuses and fails closed.
var legacy = new TestProof(clock);
publisher.TryPublish([Update(second, legacy)]).ShouldBeFalse();
legacy.Invalidations.ShouldBe(1);
}
private sealed class TestProof(TimeProvider clock) : IProjectedSamplePublicationProof
{
internal int Invalidations;
public TimeProvider Clock => clock;
public bool IsValid => true;
public bool IsSourceValid => true;
public object SourceIdentity { get; } = new();
public void Invalidate() => Invalidations++;
}
}
@@ -0,0 +1,81 @@
using System.Diagnostics;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #994 perf harness (opt-in: <c>OTOPCUA_GRPCDATA_PERF=1</c>, <c>Category=Perf</c>): a 10k-item projected cohort opened against
/// a real origin session, a sustained value publish through it, and the write-registry claim cost. Numbers go to the test
/// output; the assertions are loose sanity bounds only.
/// </summary>
[Trait("Category", "Perf"), Trait("Issue", "994")]
public sealed class GrpcDataWave3PerfTests(ITestOutputHelper output)
{
private static bool Enabled => Environment.GetEnvironmentVariable("OTOPCUA_GRPCDATA_PERF") == "1";
[Fact(Timeout = 300000)]
public async Task Cohort_of_10k_items_opens_and_carries_a_1k_values_per_second_publish()
{
Assert.SkipUnless(Enabled, "set OTOPCUA_GRPCDATA_PERF=1");
const int items = 10_000;
using var fixture = new CohortScaleFixture(items, maxBatchItems: 1000);
using var access = fixture.Create(items + 16);
var demands = fixture.AcquireAll(access);
try
{
var allocated = GC.GetTotalAllocatedBytes(precise: true);
var watch = Stopwatch.StartNew();
await using (fixture.PumpClock())
{
foreach (var demand in demands) access.StartSubscription(demand, TimeSpan.FromMilliseconds(100)).ShouldBeTrue();
await fixture.WaitForAsync(() => fixture.Baselines.Count == items, TimeSpan.FromSeconds(60), "10k baselines");
}
var open = watch.Elapsed;
var openAllocated = GC.GetTotalAllocatedBytes(precise: true) - allocated;
var commands = fixture.Commands.Count;
output.WriteLine($"open: {items} items in {open.TotalMilliseconds:F0} ms, {commands} commands " +
$"({fixture.Commands.Count(c => c is ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ChallengeSubscriptionFreshness)} freshness challenges), " +
$"{fixture.Opens} stream(s), {openAllocated / (1024 * 1024)} MiB allocated");
// 1k values/s: 100 source versions 1 ms apart on the fixture clock (1,000 changes/s). The fixture's items share one
// origin source, so each change fans out to every item at its 100 ms publishing interval; count delivered item values.
var before = Volatile.Read(ref fixture.Publishes);
allocated = GC.GetTotalAllocatedBytes(precise: true);
watch.Restart();
const int versions = 100;
for (var version = 2; version < 2 + versions; version++)
{
fixture.PublishVersion(version, version);
fixture.Origin.Clock.Advance(TimeSpan.FromMilliseconds(1));
await Task.Delay(1, TestContext.Current.CancellationToken);
}
await using (fixture.PumpClock())
await fixture.WaitForAsync(() => fixture.Latest.Values.All(v => v == 1 + versions), TimeSpan.FromSeconds(60), "final version everywhere");
var publish = watch.Elapsed;
var delivered = Volatile.Read(ref fixture.Publishes) - before;
var publishAllocated = GC.GetTotalAllocatedBytes(precise: true) - allocated;
output.WriteLine($"publish: {versions} source versions -> {delivered} item values delivered in {publish.TotalMilliseconds:F0} ms " +
$"({delivered / Math.Max(0.001, publish.TotalSeconds):F0} values/s), {publishAllocated / Math.Max(1, delivered)} B allocated per value");
fixture.Opens.ShouldBeLessThanOrEqualTo(3);
}
finally { foreach (var demand in demands) demand.Dispose(); }
}
[Fact(Timeout = 120000)]
public void Write_registry_claim_against_a_retention_full_table()
{
Assert.SkipUnless(Enabled, "set OTOPCUA_GRPCDATA_PERF=1");
var clock = new ManualTimeProvider();
var registry = new WriteOperationRegistry("inc", 20_000, 256L * 1024 * 1024, TimeSpan.FromSeconds(30), clock);
var hash = new byte[32];
for (var i = 0; i < 5000; i++) { BitConverter.GetBytes(i).CopyTo(hash, 0); registry.Claim("p", "op-" + i, "inc", hash); }
var allocated = GC.GetAllocatedBytesForCurrentThread();
var watch = Stopwatch.StartNew();
for (var i = 0; i < 2000; i++) { BitConverter.GetBytes(100_000 + i).CopyTo(hash, 0); registry.Claim("p", "more-" + i, "inc", hash); }
output.WriteLine($"registry: 2000 claims against 5000-7000 retained entries in {watch.Elapsed.TotalMilliseconds:F1} ms, " +
$"{(GC.GetAllocatedBytesForCurrentThread() - allocated) / 2000} B allocated per claim");
}
}
@@ -0,0 +1,193 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>#994: the small Wave 3 fixes (review 2026-12-02 R-12, R-21, R-22, R-23, R-24).</summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "994")]
public sealed class GrpcDataWave3SmallFixTests
{
private static byte[] Hash(int seed)
{
var hash = new byte[32];
BitConverter.GetBytes(seed).CopyTo(hash, 0);
return hash;
}
// R-21: every Claim used to copy and scan the WHOLE table (ToArray + CanRetire per entry) under the registry lock.
[Fact]
public void R21_a_claim_against_thousands_of_retained_entries_does_not_copy_the_table()
{
var clock = new ManualTimeProvider();
var registry = new WriteOperationRegistry("inc", 10_000, 64L * 1024 * 1024, TimeSpan.FromSeconds(30), clock);
for (var i = 0; i < 5000; i++) registry.Claim("p", "op-" + i, "inc", Hash(i)).Kind.ShouldBe(WriteClaimKind.Owner);
registry.Claim("p", "warm", "inc", Hash(-1));
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 100; i++) registry.Claim("p", "more-" + i, "inc", Hash(10_000 + i)).Kind.ShouldBe(WriteClaimKind.Owner);
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
// A 5,000-entry KeyValuePair copy is ~200 KB per claim (~20 MB for 100); a claim itself is well under 2 KB.
allocated.ShouldBeLessThan(2_000_000, $"allocated {allocated} bytes for 100 claims");
}
[Fact]
public void R21_retirement_still_happens_past_retention_and_at_capacity()
{
var clock = new ManualTimeProvider();
var registry = new WriteOperationRegistry("inc", 2, 64 * 1024, TimeSpan.FromSeconds(30), clock);
var first = registry.Claim("p", "a", "inc", Hash(1)).Claim!;
var second = registry.Claim("p", "b", "inc", Hash(2)).Claim!;
registry.Claim("p", "c", "inc", Hash(3)).Kind.ShouldBe(WriteClaimKind.Capacity, "both entries are still live");
first.TryMarkDispatched().ShouldBeTrue(); first.Complete(new(DataWriteState.OutcomeUnknown, 0x80000000u, null)).ShouldBeTrue();
first.PhysicalFinished();
second.Complete(new(DataWriteState.RejectedBeforeDispatch, 0x80000000u, null)).ShouldBeTrue();
registry.Claim("p", "a", "inc", Hash(1)).Kind.ShouldBe(WriteClaimKind.Existing, "inside retention a duplicate joins");
clock.Advance(TimeSpan.FromSeconds(31));
// Capacity is never refused while a retirable entry remains, and a reused id past retention is a fresh owner.
registry.Claim("p", "c", "inc", Hash(3)).Kind.ShouldBe(WriteClaimKind.Owner);
registry.Claim("p", "a", "inc", Hash(9)).Kind.ShouldBe(WriteClaimKind.Owner);
}
// R-22: a request still holding a session that a channel close / LRU eviction cleared stored its chunk in the orphan;
// nothing ever swept it, so its bytes stayed charged to the principal until restart.
[Fact]
public void R22_a_chunk_saved_into_a_cleared_session_is_refused_and_charges_nothing()
{
var sessions = new OriginHistorySessions(TimeProvider.System);
var caller = new DataAuthenticatedContext("a", "key-a", "v1", null, 1);
var session = sessions.Get(caller, new DataHistoryChannel("c", CancellationToken.None), 4);
var view = new DataView(new("c", "u", "string", "x"), DataRealm.Raw, null, 0, "x");
session.Clear(); // the channel closed while a request was between its last check and SaveChunk
session.SaveChunk(new OriginHistorySession.Chunk(view, "k", "i", [], 0, null, null, 0, 100), 1000).ShouldBeNull();
sessions.RetainedBytes("a").ShouldBe(0);
// Positive control: a live session still stores and charges.
var live = sessions.Get(caller, new DataHistoryChannel("d", CancellationToken.None), 4);
live.SaveChunk(new OriginHistorySession.Chunk(view, "k", "i", [], 0, null, null, 0, 100), 1000).ShouldNotBeNull();
sessions.RetainedBytes("a").ShouldBe(100);
}
// R-23: the worker checked "is a snapshot incomplete" under the gate, released it, THEN armed the barrier; a SnapshotEnd
// committed in between found the barrier unarmed (its release a no-op) and the later arm stuck every following command
// until its acknowledgement timeout. The hook runs where that window was and completes the snapshot inside it.
[Fact(Timeout = 30000)]
public async Task R23_a_snapshot_completing_right_after_the_barrier_decision_still_releases_the_deferred_modify()
{
var ct = TestContext.Current.CancellationToken;
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(10);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(ct);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var sink = new HeldFirstSnapshotEndSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().RunDeliveryAsync(sink, ct);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), ct);
await sink.FirstSnapshotEndHeld.Task.WaitAsync(ct); // the open's snapshot is not complete yet
using var committed = new ManualResetEventSlim();
session.SnapshotEndReleasedForTests = committed.Set; // after the commit decided (and ran) its barrier release
var decided = 0;
session.AfterSnapshotBarrierCheckForTests = () =>
{
if (Interlocked.Exchange(ref decided, 1) != 0) return;
sink.ReleaseFirstSnapshotEnd();
committed.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
};
await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings with { Deadband = 5 })]), ct);
await Task.WhenAny(sink.ModifyAck.Task, writer).WaitAsync(TimeSpan.FromSeconds(4), ct);
Volatile.Read(ref decided).ShouldBe(1, "positive control: the modify was deferred behind the open's snapshot");
sink.ModifyAck.Task.IsCompleted.ShouldBeTrue("the deferred modify must run once the snapshot completed: " + string.Join(" | ", sink.Frames));
}
}
private sealed class HeldFirstSnapshotEndSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource FirstSnapshotEndHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource ModifyAck = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly System.Collections.Concurrent.ConcurrentQueue<string> Frames = new();
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _ends;
internal void ReleaseFirstSnapshotEnd() => _release.TrySetResult();
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame));
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
var frame = ((Prepared)prepared).Frame;
Frames.Enqueue(frame switch
{
DataSubscriptionAck ack => "ack:" + ack.CommandId,
DataSubscriptionControl control => control.Kind + (control.Diagnostic is { } d ? ":" + d : ""),
_ => frame.GetType().Name
});
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd } && Interlocked.Increment(ref _ends) == 1)
{
FirstSnapshotEndHeld.TrySetResult();
await _release.Task.WaitAsync(cancellationToken);
}
if (frame is DataSubscriptionAck { CommandId: "modify" }) ModifyAck.TrySetResult();
}
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}
// R-24: the condition stream left a MoveNextAsync pending across iterations and then disposed the async iterator with
// `await using` — which throws NotSupportedException mid-MoveNext, replacing the stream's real failure.
[Fact]
public async Task R24_teardown_of_a_pending_frame_read_neither_throws_nor_leaves_the_read_unobserved()
{
var ct = TestContext.Current.CancellationToken;
// Positive control: the language behaviour the old teardown hit.
var naive = Frames(ct).GetAsyncEnumerator(ct);
var naivePending = naive.MoveNextAsync().AsTask();
await Should.ThrowAsync<NotSupportedException>(async () => await naive.DisposeAsync());
_ = naivePending.ContinueWith(static t => _ = t.Exception, TaskScheduler.Default);
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
var frames = Frames(stop.Token).GetAsyncEnumerator(stop.Token);
var pending = frames.MoveNextAsync().AsTask();
await ProjectedStreamTeardown.StopAsync(stop, pending, frames); // must not throw
pending.IsCompleted.ShouldBeTrue("the pending read was cancelled and observed before disposal");
stop.IsCancellationRequested.ShouldBeTrue();
}
private static async IAsyncEnumerable<int> Frames([System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken token)
{
await Task.Delay(Timeout.Infinite, token);
yield return 1;
}
// R-12: each delivered value frame ran the full catalog-resolve + export-ancestry + ACL walk 3-4 times (once under the
// session lock). The verdict is now memoised per (catalog instance, authority generation) for at most a second.
[Fact]
public void R12_the_publish_verdict_is_evaluated_once_per_catalog_and_authority_and_a_revocation_still_lands_at_once()
{
using var fixture = new LocalDataFixture();
var target = new DataTarget(DataTargetMode.Node, "cluster", fixture.Serving.NodeId);
fixture.Services.AuthorizeSubscription(fixture.Context, target, fixture.Raw, out var view).ShouldBe(DataItemStatus.Good);
var before = fixture.Services.PublishVerdictEvaluationsForTests;
for (var i = 0; i < 1000; i++) view!.CanPublish().ShouldBeTrue();
(fixture.Services.PublishVerdictEvaluationsForTests - before).ShouldBe(1, "one walk serves every frame of this authority");
fixture.Clock.Advance(LocalDataServices.PublishVerdictTtl);
view!.CanPublish().ShouldBeTrue();
(fixture.Services.PublishVerdictEvaluationsForTests - before).ShouldBe(2, "re-proved once the TTL passed");
// An authority publish (here: the grant withdrawn) misses the memo on the very next frame.
var key = new ZB.MOM.WW.OtOpcUa.Configuration.Entities.ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
fixture.Authority.Apply("cluster", "revoked", [key], [], new Dictionary<ZB.MOM.WW.OtOpcUa.Core.Authorization.AclScopeRef,
IReadOnlyList<ZB.MOM.WW.OtOpcUa.Core.Authorization.NodeAclPath>>());
view.CanPublish().ShouldBeFalse("a revocation is never served from the memo");
}
}