# Description Bound managed-session recovery, preserve Publish workers and recovery ownership, and address the client, server, transport, and certificate audit findings and subsequent concurrency review. Also reduce the memory retained by exhaustive session-test diagnostics. ## Recovery and Publish ownership - Add `ManagedSessionOptions.ChannelReconnectTimeout` through direct construction, the fluent builder, and DI. The automatic duration is `max(3 * KeepAliveInterval, revised SessionTimeout, OperationTimeout)`, sampled at cycle start. Positive overrides are supported; `Timeout.InfiniteTimeSpan` explicitly opts out. Raw sessions retain their unlimited default. - Add `CreateReconnectBudget(TimeProvider)` as a required `IReconnectParticipant` member, as agreed in review. Custom participants implement it and may return null for no participant-specific bound. - Enforce the earliest participant/caller deadline through transport reconnect, activation/recreation, and subscription restoration. Late callers can shorten an active cycle but cannot extend it. - Cancel and unwind recovery, fence late responses, and release channel recovery ownership before the existing `Faulted` event hands control to the outer reconnect/failover policy. Preserve session recreate admission through final Publish cleanup and keepalive suppression until shared recovery is complete. - Treat participant budget creation/evaluation failures, including exceptions at the exact deadline, as terminal shared-recovery failures. Notify participants before exposing `Faulted`, preserve the original diagnostic, and never silently replace a finite budget with unlimited recovery. - Keep caller-supplied replacement channels, managed bindings, wrapper event subscriptions, and recovery-owner identities consistent across success, failure, and cancellation. Reject replacement during active recovery and fence retired callbacks so they cannot clear newer ownership or suppress later keepalive recovery. - Retain eligible Publish workers through temporary subscription-identifier clearing without retaining workers for never-created or removed subscriptions. Preserve cancellation, acknowledgement rollback, and drain-before-replacement ordering. - Coordinate automatic subscription updates with session recovery: cancel admitted updates, keep them paused across a failed-restoration handoff, and retry only after explicit restoration completes. This prevents competing CreateSubscription requests and updates against a retiring session, while preserving manual recreation, transfer fallback, and pending option changes. - Exercise the real ManagedSession, V2 subscription engine, and channel ready gate with scripted transports and an injected clock. Cover transfer fallback, deadline handoff, late completions, and resumed notification delivery. ## Audit and review corrections - Correct certificate/trust-list transactions, change-pump lifetimes, validation, peer revalidation, and reset/resource ownership. - Harden node admission, attribute/range/dimension validation, monitored-item sampling and lifecycle transitions, event fanout, and server shutdown. Run lifecycle readiness and compensation outside shared monitored-item admission, with stale-completion ownership checks. - Close synchronous node-manager admission before teardown and retain resources until admitted service, lifecycle, and asynchronous method work returns. Dispose the monitored-item manager outside both locks, reject late calls before they can reach it, and forward asynchronous disposal through the adapter so the master awaits the same completion. Preserve reentrant shutdown initiation, cancellation/failure unwinding, and shared cleanup-failure reporting. - Bound WSS pending-request retention using connection-local wire handles while preserving caller-visible request handles and translating Cancel targets. Safely ignore retired replies and drain admitted send/close users before resource disposal. - Clarify that the shared `ClientBase` caller-handle sequence is distinct from the non-wrapping WSS wire allocator. Existing exhaustion/reopen, late-reply, and Cancel-translation regressions verify the connection-local contract; no allocator behavior was changed by this clarification. - Preserve virtual-node validation and resolver service errors instead of converting them to cached misses. A mismatched NodeId reports `BadNodeIdInvalid`; callback type mismatches and resolver service errors keep their exact status. Per-item boundaries preserve unaffected reads, writes, history operations, method calls, browse paths, and monitored-item creation/restoration, including permission-validation paths. Caller cancellation still propagates; stored-item validation failures are logged without aborting later restores. - Correct client file/role/state-machine/streaming APIs, node-cache behavior, redundancy/failover ownership, and session configuration/identity handling. - Cancel each owned peer-discovery scope before disposing it, including when the bounded wait wins a cancellation-delivery race. Keep late results out of the endpoint cache and preserve single-flight lookup ownership. - Keep materialized alias Browse results synchronized with the live store by default, preserving explicit startup-only opt-out. Apply HistoryUpdate service results per value while retaining explicit all-or-nothing provider APIs. - Update the directly related feature documentation and add focused positive, negative, concurrency, and ownership regressions. ## Latest review-feedback corrections - Fence stale failed lease observations with a successful-confirmation generation distinct from the revocation epoch. Snapshot it before each store read, including failed-CAS revalidation, so an old failure cannot revoke or reschedule a newer lease while fresh ownership loss still revokes leadership. Preserve independent overlapping acquisitions, expiry, disposal, and late-success protections. - Isolate attributable WSS response-decoding errors to their request, including retired handles. Keep admitted socket sends connection-owned so caller timeout/cancellation cannot abort sibling requests; shutdown still cancels and drains those sends. - Restart keepalive and classic Publish replenishment after successful session reuse. Retire V2 worker demand after intentional deletion/disable without confusing that state with temporary recovery resets. - Browse virtual directories lazily across continuation pages without the 1,024-entry snapshot cap. Preserve active-page cancellation, bounded metadata retention, pushback, and exactly-once asynchronous cursor cleanup. - Apply certificate/CRL staging in last-operation order, preflight required issuer storage before writes, select actual policy-compatible RSA keys for None endpoints, frame certificate chains independently of signature OIDs, and preserve admitted validation results during rejected-writer shutdown. - Preserve base asynchronous disposal when a legacy override omits its base call; avoid double derived disposal in the adapter. Let genuinely admitted nested work finish while rejecting stale captured contexts and returning null from closed lookup APIs. - Re-park recovered monitored items if AddNodes rolls back. Give event compensation a fresh finite deadline, and preserve healthy Browse/Translate siblings at every reference/path boundary while retaining starting-node errors and caller cancellation. - Give final reconnect notifications a live, bounded shutdown-linked lifetime. Synchronize child state before parent lifecycle handlers outside the parent transition lock. - Document the accepted existing policies: direct reverse connections are single-use without a ReverseConnectManager, and multi-node stream capacity is shared rather than reserved per node. The expanded readiness controls also exposed a real generation-handoff race: an old source could finish draining after activation was deferred but before readiness tasks were collected, causing the wanted replacement to be omitted from the wait set. A deterministic test gates that exact interval; the fix keeps the replacement in the readiness wait. The original race passed 200 repetitions after the fix. A separate control now awaits both producer readiness and iterator entry under the same original deadline, rather than treating those independent signals as equivalent. Temporary logging and repetition are removed. ## CI integration contracts The History and Server CI failures exposed integration tests that still asserted the behavior intentionally changed by the audit fixes. A Windows WoT negative test raced its caller deadline against upstream retries. A subsequent Ubuntu Client failure exposed a real automatic-update versus explicit-restoration race: - History insertion collisions now verify exact per-value statuses and all persisted timestamps/values, including preservation of the existing conflicting entry. Explicit atomic-provider rollback controls remain. - Alias materialization tests wait for actual publication and verify the added node plus forward/inverse `AliasFor` references, instead of racing a startup-only snapshot expectation. Explicit refresh opt-out controls remain. - The unavailable-upstream WoT test uses an explicit finite retry policy through existing DI configuration, preserving its original four-minute guard and requiring a mapped-value service error before caller cancellation. Production retry defaults remain unchanged. - The Client fix retains the exact one-create and late-response assertions. Three deterministic real-subscription/real-manager cases cover paused creation, disposal while paused, and cancellation of an admitted create followed by explicit restoration and a pending option update. Both composed restoration-deadline cases also prove automatic updates stay blocked at the outer handoff and resume after restoration. - The merged-head net48 correction prevents lost peer-resolver cancellation and distinguishes the harness's delayed initial `Connected` event from actual outer recovery completion. A deterministic timer-order test covers both cooperative and cancellation-ignoring resolvers, cancellation before return, rejection of late cached results, and a fresh subsequent lookup. - The remaining CodeQL alert was a false content flow through `ArrayOf.Count` into an integer-only trust-list summary. Projecting the same count through `Span.Length` keeps cardinality distinct from serialized contents without allocating, dropping diagnostics, suppressing the rule, or dismissing the alert. Five log-contract cases cover null/empty/nonempty results and mixed chain-capable/fallback listeners, asserting the exact count, message, and structured properties. - Classic transfer acknowledges messages selected for asynchronous Republish only after their responses arrive. The existing locked replay-selection decision returns the immediate-acknowledgement subset to Session, preserving the public transfer API, advertised availability, and immediate acknowledgement of older gapped messages not selected for replay. A callback changing `RepublishAfterTransfer` cannot change the already-selected acknowledgement ownership. - Transfer integration tests explicitly control acknowledged versus retained origin messages. Exact assertions distinguish retained replay from requested fresh initial values by sequence number, client handles, values, status, and source timestamp. Atomic counters, observed delivery/keepalive progress, and failure-safe session/file cleanup replace timing assumptions and racy resets. - Server lifecycle tests verify the documented independent five-second compensation deadline rather than requiring a non-cancellable token. They cancel the actual request, prove compensation and unrelated monitored-item creation still proceed one tick before the deadline, preserve the original failure and ownership assertions, and verify the completed deadline is retired. - Synchronous and asynchronous directory-browser tests require the exact provider exception instead of an empty-directory success, then verify the failed cursor is not enumerated again. These correct expectations left behind by the intentional, documented provider-error propagation change; production behavior is unchanged. No tests were disabled, assertions loosened, coverage thresholds lowered, or CI checks made optional. Existing platform exclusions and Explicit debug variants remain. ## Related Issues - Fixes #4514 - Fixes #4515 - Builds on merged #4503 and retains the #4508 publishing-drain behavior. ## Validation **Lease-election review correction (`a13afa641182c70983e16bbcfebf507e666a45a5`):** The correction is based on the existing upstream merge `43079e2b851fe338a4082066f8d14abfdafb6e32`. Three deterministic stale-verdict cases fail on the original source and pass with separate confirmation fencing. Six new cases cover the initial foreign-owner verdict, failed-CAS revalidation in both invocation orders, and fresh ownership loss through both read paths, including revalidation begun after another successful confirmation. | Target and configuration | Passed | Failed | Skipped | | --- | ---: | ---: | ---: | | net10.0 Debug | 120 | 0 | 0 | | net48 Debug | 120 | 0 | 0 | The selection is the full `Opc.Ua.Core.Tests.Redundancy` namespace, including all 38 `SharedStoreLeaseElectionTests` cases and the existing expiry, clock rollback, disposal, and overlapping-success regressions. New witnesses are `StaleForeignLeaseReadDoesNotRevokeNewerAcquisitionAsync`, `StaleFailedRevalidationDoesNotRevokeNewerAcquisitionAsync`, and `FreshForeignLeaseObservationRevokesLeadershipAsync`. They assert resulting leadership, exact transitions, independent progress, and the unchanged expiry boundary. Retaining the initial generation for the fallback read independently makes the fresh-loss-after-confirmation control fail; that mutation was removed before the final rebuilt runs. The successful scoped command is `dotnet test tests\Opc.Ua.Core.Tests\Opc.Ua.Core.Tests.csproj -c Debug --no-restore --filter "FullyQualifiedName~Opc.Ua.Core.Tests.Redundancy"`, with `CustomTestTarget` and `-f` matching each row and that framework's assets restored. Both changed C# files pass formatting and analyzers through informational severity on both frameworks. These are scoped results, not a full-solution test or measured coverage-delta claim. CI monitoring is paused for this feedback-only operation; no current-head CI success is claimed. **Latest CI contract correction (`1cd1f2047bb5b50c9bf300b1ff710b0b2e935a29`):** All four failing Server shard 23 jobs in [run 36120946740](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/36120946740) reported the same six cases. Two local replays reproduced all six failures. The source changes and documentation from `cd43b831a` establish both intentional contracts: independent bounded event compensation and surfaced provider errors. Only the two test files are corrected; production code and CI policy are unchanged. | Target and configuration | Passed | Failed | Skipped | | --- | ---: | ---: | ---: | | net48 Debug | 113 | 0 | 0 | | net10.0 Release, CI Coverlet settings | 113 | 0 | 0 | The selection contains `MonitoredItemManagerLifecycleTests`, `DirectoryObjectStateTests`, `DirectoryBrowserBoundedEnumerationTests`, and `EventCompensationReadinessHasFiniteDeadlineWithInfiniteSourceTimeoutAsync`. Both changed files pass formatting and analyzers through informational severity on both frameworks. Independent mutations restoring a non-cancellable compensation token and swallowing provider errors fail all four lifecycle cases and both browser cases, respectively. Both mutations were removed before the final passing runs and commit. The scoped command is `dotnet test tests\Opc.Ua.Server.Tests\Opc.Ua.Server.Tests.csproj` with `CustomTestTarget` and `-f` set to the selected framework, `--no-restore`, and `--filter "FullyQualifiedName~MonitoredItemManagerLifecycleTests|FullyQualifiedName~DirectoryObjectStateTests|FullyQualifiedName~DirectoryBrowserBoundedEnumerationTests|FullyQualifiedName~EventCompensationReadinessHasFiniteDeadlineWithInfiniteSourceTimeoutAsync"`. The modern run additionally uses `-c Release /p:CollectCoverage=true --collect "XPlat Code Coverage" --settings tests\coverlet.runsettings.xml`. These are scoped results, not a full-solution test or measured coverage-delta claim. Hosted checks for that commit were pending at publication. The fail-fast CI watch was stopped when the requested operation switched to review feedback; no current-head CI success is claimed. **Earlier master merge (`8b15ea6ef9fc2214ac8ec886f373bb3846dd6d6f`, base `b4136d8e9bab0df680f41d9ef985f519160534b1`):** The `TcpListenerChannel` conflict preserves both lifetime responsibilities: disposal clears the retained peer-certificate chain and unregisters the quota-scoped message-assembly scheduler. Both fields and all upstream deadline handling remain intact. The only additional manual source adjustment adds the parentheses required by the existing analyzer around the session-count fallback. Master advanced during validation. The initial transport merge `80303c434ce813cf75aa7fe54a6a32fe2aeafc30` was retained, and the newer base was merged normally in `8b15ea6ef9fc2214ac8ec886f373bb3846dd6d6f`, without rewriting history. The additional recovery, fluent-pipeline, and test-framework overlaps were inspected; the branch's cancellation, validation-error, and acknowledgement ownership fixes remain alongside the upstream changes. Full `UA.slnx` builds passed on net10.0 and net48 with **0 warnings and 0 errors**. The final scoped tests rebuilt against the committed tree `2074f8efcb61d8d9c6106e7d6f76ee941940e358`: | Target | Passed | Failed | Skipped | | --- | ---: | ---: | ---: | | net10.0 | 2,653 | 0 | 0 | | net48 | 2,529 | 0 | 7 | The net48 skips are existing platform exclusions: six RSA_DH_AesGcm nonce cases and one ClientWebSocket certificate-validation case requiring .NET 7 or later. The selection covers transport cleanup, reassembly budgets/deadlines/admission, peer-chain ownership, server session binding, fluent lifecycles and source generation, reconnect and keepalive, transfer acknowledgements, Publish queues, and JSON encoding. Modern-.NET WSS transport and real-server integration cases also pass. The resolved file passed solution-relative formatting and analyzer verification through informational severity on both frameworks. These are scoped test results, not unfiltered full-suite or measured-coverage claims. Hosted CI was not monitored or repaired as part of this merge-only operation. Selected local results below are overlapping validation runs, not distinct-test totals. **Earlier review-feedback batch (`cd43b831a8f11de3f7d65c3681712a61e3c669a5`):** The final net10.0 scoped selection passed **471 tests, with no failures or skips**. The final net48 solution-root selection passed **439 tests, with no failures and one unchanged platform skip** (`ValidateServerCertificateFallsBackToTlsPolicyErrors`, which requires newer ClientWebSocket certificate-validation support). Both full nonincremental solution builds completed with **0 warnings and 0 errors**, and all **40 changed C# files** passed informational-level formatting/analyzer verification. Both frameworks validated the identical final tracked diff. The focused matrix covers every one of the 20 current review threads, including real mid-frame WSS cancellation, stale admission contexts, directory continuation ownership, multi-element Browse/Translate failures, and the readiness drain race. The net10.0 solution-root test command has a separate pre-existing runner conflict: three unrelated AOT projects reject the VSTest target under Microsoft.Testing.Platform 2.4.0 and SDK 10. Per-project net10.0 results are recorded separately; no runner migration, test exclusion, assertion relaxation, or CI-policy change is included. These are bounded selections, not unfiltered full-suite or measured coverage claims. At publication of `cd43b831a`, hosted CI was not green: the `OPCFoundation.UA-.NETStandard` check reported `ACTION_REQUIRED`, AppVeyor reported `FAILURE`, and the two signed-build jobs were in progress. No CI jobs were rerun, cancelled, approved, or repaired as part of that feedback-only operation. **Classic transfer correction (`f425376fca045794122e19aaf9cafebc4a717d91`):** The preceding head's [macOS net10.0 shard 25/30](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/35980326299/job/107570512458) failed `TransferSubscriptionTest(DisconnectedRepublish).TransferSubscriptionAsync(True,False)` at the static-node count assertion: expected 10, received 20. The trace contains a successful, explicitly requested republish of retained sequence 1 and a fresh initial-value batch at sequence 3, not duplicate dispatch of one response. Controlled lost origin acknowledgements reproduced that incorrect test expectation on both the preceding PR head and exact master base `a2539cb53dd1666cef856f33812d7a8830d68909`. The maintainer explicitly authorized correcting this existing issue in the PR. Retained replay and requested initial values are independent, as specified by [OPC UA Part 4, TransferSubscriptions](https://reference.opcfoundation.org/specs/OPC-10000-4/5.14.7). The reason that the original hosted run retained its particular origin message remains unproved. The expanded full-suite run then exposed a **real production race**, not just a count assertion: Session queued acknowledgements for all transferred available messages before the asynchronous Republish responses arrived. Publish could delete those messages first, causing `BadMessageNotAvailable`. A gated real-Session/classic-engine regression failed both replay-enabled cases on the original implementation while both no-replay controls passed. The ownership fix passes all 24 combinations of empty/consecutive/unsorted-gapped queues, replay preference, sequential delivery, and a reentrant preference change. All 40 normal real-server transfer cases pass on both frameworks. Independent mutations suppressing actual replay and duplicating observed sequence records each fail the intended assertion; both mutations were removed. The full classic suite passes on both frameworks. Hosted CI was pending when that correction was published; the earlier failed hosted job was not rerun for a lucky pass. **Local net48 caveat:** the full Client run timed out in the pre-existing fake-clock test `ReconnectAsyncSwapsFaultedLeaseEntryAsync`, which does not exercise subscription transfer. Its unchanged isolated replay passed, but that does not resolve the full-suite timeout. No unrelated code or assertions were changed, and a clean full Client net48 run is not claimed. | Scope | net10.0 | net48 | | --- | --- | --- | | Full Client.Tests after transfer acknowledgement correction | 2,549 passed | 2,552 passed, 1 timeout failure noted above, 1 existing platform skip | | Full classic-subscription project after transfer correction | 57 passed, including all 40 normal transfer cases | 57 passed, including all 40 normal transfer cases | | Gated transferred-message acknowledgement ownership | 24 passed, included above | 24 passed, included above | | Saved-session consumer of the shared subscription helper | 40 passed | 16 passed, 24 existing unsupported-security-policy skips | | Audit regression matrix | 2,339 passed | 1,934 passed, 34 existing skips | | Full Client.Tests after review follow-ups | 2,520 passed | Focused selections only | | Full Client.Tests after CI recovery correction | 2,523 passed, CI coverage collector | 2,527 passed, 1 existing platform skip | | Latest merged-head recovery/redundancy selection | 139 passed | 139 passed | | Full Client.Tests after merged-head net48 correction | Focused selection above | 2,529 passed, 1 existing platform skip | | Lifecycle and actual-dimension regressions | 146 passed | 146 passed | | Focused recovery follow-ups | 7 passed | 7 passed | | WSS-related fixtures | 93 passed | Not applicable | | CI History integration corrections | 28 passed | 28 passed | | CI alias, dispatcher, and explicit-atomic controls | 63 passed | 63 passed | | Full WoT sample project with CI coverage collector | 29 passed | Not applicable | | Trust-list effects and count-only summary contract | 22 passed | 22 passed | | Virtual-node feedback, node-manager, dispatcher, and lifecycle selections | 661 passed, 63 existing not-executed cases; all 48 virtual-node cases passed | 661 passed, 63 existing not-executed cases; all 48 virtual-node cases passed | | WSS wire-handle exhaustion, late replies, and Cancel translation | 9 passed | Not applicable | | Synchronous node-manager disposal and related service/lifecycle suites | 1,037 passed, 64 not-executed cases from existing fixture assumptions; all 93 sampling/disposal cases passed | 1,037 passed, 64 not-executed cases from existing fixture assumptions; all 93 sampling/disposal cases passed | - Full solution builds passed on net10.0 and net48 during the audit work. The subsequent full non-incremental net10.0 build also completed with zero warnings/errors. - Modified source/test formatting and analyzer checks passed through informational severity. - Original composed recovery regressions passed repeated runs on both frameworks. Independent mutations removing Publish cancellation, bypassing the recreate drain call, or ignoring ready-gate cancellation each failed the intended assertion; all mutations were restored before passing runs. - The latest recovery correction passed 100 executions of each original restoration-deadline scenario with unchanged assertions. Restoring premature update admission independently made both strengthened handoff cases fail; the correct retention behavior was restored afterward. - Startup-event and cancellation-delivery timing probes reproduced the subsequent net48 failures, then passed 100 executions of each of the three scenarios with the fixes. All timing probes and repetition were removed. The permanent timeout-order regression also went RED on the original cancellation cleanup without sleeps or scheduling amplification. - Final post-format recovery/subscription/engine checks passed all 151 selected cases on net10.0. The first local full net48 attempt aborted in `clr.dll` with native access violation `0xc0000005`; an unchanged-assembly full diagnostic rerun passed as recorded above. That native host crash has not been attributed or claimed fixed. - A minimal replay with the same CodeQL CLI and query-pack versions reproduced the custom-count alert and confirmed that the standard span-length projection is clean while direct sensitive-value and raw-identifier logging controls remain flagged. The source was already logging only a count; no identifier or certificate disclosure was established at the reported location. - The virtual-node feedback regressions first reproduced five error-preservation/cache failures; expanded service-dispatch cases exposed two additional whole-batch failures before the operation-boundary fixes. The final selections pass on both frameworks. Genuine misses remain cached, successful results remain reusable, failed validation allows same-cache retry, and request cancellation still stops the batch. - Three deterministic synchronous-manager disposal regressions reproduced early resource release and lifecycle calls reaching a manager during disposal. The fix passes direct and adapted calls, a sampling-worker join after the last operation exits, reentrant shutdown, cancellation and failure paths, repeated disposal, and exact rejection across 39 service/lifecycle entry points both during drain and after cleanup. The original outside-node-lock disposal regression remains and now requires the worker to observe closed admission. - Prior-head CI on `c985f8bded77a60449d9cd381c8a004d8590ccf6` completed with **168 passing checks, one expected release-package-publication skip, and no failures or pending checks**. All test shards, signed builds, container builds, the coverage check, and the CodeQL PR check passed. Hosted CodeQL analysis `1829262912` completed successfully and marks count-flow alert 385 fixed. This is evidence for that head, not a claim that subsequent review follow-ups have completed hosted CI. ### Session-test diagnostic memory Complete browse listings are streamed to unique NUnit attachments rather than retained in inline NUnit/VSTest output. Detached regression-test results are cleaned up without deleting runner-collected attachments. - Two covered session-suite runs each completed with 782 passed and 379 existing skips. Peak working set fell from 4.86 GiB to 2.44-2.78 GiB. - TRX output shrank from 303.1 MiB to approximately 40.7 MiB, retaining all 46 complete browse attachments. - Seven output regressions cover exact content, empty/single/large listings, disabled/enabled output, bounded inline summaries, and unique filenames. The separate Azure build-18452 VM deprovisioning cause remains unproved without provider logs. The memory measurements do not establish its cause. Unfiltered local `UA.slnx` tests, including the long stress/soak suites, have not been run on both frameworks. A local coverage delta was not collected; builds and focused tests are not substitutes for those claims. ## Checklist - [ ] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [ ] I have added tests that prove my fix is effective or that my feature works and increased code coverage. - [x] I have added all necessary documentation. - [x] I have verified that my changes do not introduce (new) build or analyzer warnings. - [ ] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. - [ ] All checks on the latest review-follow-up head have completed successfully; prior-head CI passed as recorded above. - [x] I have addressed **all** PR feedback received. Tests have been added and pass as recorded above; the hosted coverage check passed on the prior head identified above. The combined tests/coverage-increase checkbox remains open because no local coverage delta was measured. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f26810-22b8-476f-abcd-0a8c82d6e208
53 KiB
Subscriptions and Monitored Items Service Set
The OPC UA Subscription and MonitoredItems service sets (Part 4 §5.13 and §5.14) are exposed through three layered client APIs in this stack:
- Classic
Opc.Ua.Client.Subscription— the historical event-driven API. Items added withsubscription.AddItem(item); subscription.ApplyChangesAsync(); notifications delivered through the per-itemNotificationevent or the per-subscriptionFastDataChangeCallback/FastEventCallback. - V2
ISubscriptionManager/ISubscription— the options-based callback API insrc/Opc.Ua.Client/Subscription/. Items added withsubscription.MonitoredItems.TryAdd(name, options, out _); notifications delivered throughISubscriptionNotificationHandlercallbacks. The default engine onManagedSession. IStreamingSubscription— a thinIAsyncEnumerable<T>abstraction on top of the V2 engine for state-machine waits and short-lived monitoring.
On the server, newly created monitored items remain provisional until the subscription rechecks ownership and deletion after node-manager creation. If transfer, session detachment, deletion, or cancellation wins, normal node-manager deletion releases those unattached items.
Publish, queued Publish, Republish, and persistence consumers receive deep notification snapshots. Acknowledgement, eviction, or queue disposal can recycle the retained pooled graph without changing a response still waiting for encoding or a captured retransmission/durable snapshot. Pooling remains enabled for the retained notifications.
Recommendation: new code should use the V2 surface
(ISubscriptionManager for long-lived application subscriptions,
IStreamingSubscription for short-lived / await-until-X scenarios).
The classic API stays supported for migration and continues to ship
in Opc.Ua.Client.Subscription; an internal bridge forwards classic
subscriptions onto the V2 publish pipeline when the V2 engine is
active, so existing classic-API code keeps working alongside V2.
For the full engine comparison (publish-pipeline ownership, worker pools, when to pick which) see Sessions.md §4.
- Quick reference
- Server retransmission queues
- Publishing during session recovery
- Triggering (SetTriggering)
- Unbounded monitored items
- Streaming subscriptions
- Classic → V2 surface mapping
- Three-API summary
Quick reference
| Concern | API |
|---|---|
| Add a V2 subscription | session.AddSubscription(handler, SubscriptionOptions) (or ISubscriptionManager.Add) |
| Add a monitored item | subscription.MonitoredItems.TryAdd(name, IOptionsMonitor<MonitoredItemOptions>, out _) (or subscription.TryAddMonitoredItem(name, nodeId, configure, out _) extension) |
| Set triggering — declarative | MonitoredItemOptions.TriggeredByNames (IReadOnlyList<string>) at item-add time |
| Set triggering — imperative | ISubscription.SetTriggeringAsync(IMonitoredItem, add, remove, ct) returning SetTriggeringResult |
| Triggering — name-based fluent | ISubscription.SetTriggeringAsync(string trigName, params string[] tgtNames) |
| Triggering — navigation | IMonitoredItem.TriggeringItems / IMonitoredItem.TriggeredItems (N:M) |
| Save / load subscriptions | session.SaveSubscriptionsAsync(stream) / session.LoadSubscriptionsAsync(stream, factory) |
| Stream — get streaming subscription | ManagedSession.DefaultStreaming |
| Stream — construct manually | new StreamingSubscription(subscriptionManager, options?) |
| Stream — subscribe one variable | streaming.SubscribeDataChangesAsync(nodeId, options?, ct) |
| Stream — subscribe many variables | streaming.SubscribeDataChangesAsync(IReadOnlyList<NodeId>, ...) |
| Stream — subscribe to events | streaming.SubscribeEventsAsync(notifierId, EventFilter, options?, ct) |
| Stream — wait until predicate | .TakeUntilAsync(predicate) |
| Stream — cap by wall-clock time | .WithTimeoutAsync(timeout) |
| Stream — take N items | .TakeAsync(count) |
| Stream — buffer first N | .BufferedAsync(count) |
| Stream — typed alarms | streaming.SubscribeAlarmsAsync(notifierId, filter?) |
Server retransmission queues
The server retains notification messages for acknowledgement and Republish (Part 4 §5.14). When a new batch exceeds the configured retransmission capacity, only the excess oldest retained messages are evicted. The remaining sequence numbers, persistence removal deltas and discarded-unacknowledged-message diagnostics describe the same retained queue. An oversized new batch is trimmed to capacity before it displaces older messages.
The per-session Publish request limit counts only requests still awaiting a response. Cancellation, timeout, normal completion and session/server teardown release a request's admission exactly once; a completed request does not prevent the client from queuing its replacement while a long keep-alive is pending.
Publish from a live session without subscriptions returns BadNoSubscription,
regardless of other sessions' subscriptions. A closing session retains
BadSessionClosed. The Republish request and requested-message diagnostic
counters remain equal, with one increment per authorized request; the
successful-message counter advances only when a message is returned.
Publishing during session recovery
V2 session recreation pauses publishing and drains active Publish attempts before replacing the session. The drain cancels each attempt, including an attempt parked at the shared channel's ready gate, without terminating its worker. A cancelled attempt rolls its acknowledgements back before releasing its active count. Recreation must await this complete unwind because a timeout that skips the drain could acknowledge notifications from the old subscription generation against a reused subscription identifier.
Automatic subscription and monitored-item updates also pause during session
recreation. Recovery cancels an active update pass; its retry waits until the
recovery owner completes subscription restoration. If restoration fails, this
pause remains in effect across the outer-policy handoff. The state worker cannot
create a competing subscription on a retiring or replacement session. Pending
option changes resume after restoration, without changing explicit
RecreateAsync or transfer semantics. Cancellation remains client-side and does
not guarantee that an already-sent request was not processed by the server.
Once the session and subscriptions are restored, publishing resumes through the
same subscription-facing interface. Temporarily clearing server-side subscription
identifiers does not replace existing workers. Pool limits and actual subscription
removal still apply. Intentional deletion, including setting the V2 subscription's
Disabled option, retires its worker demand even if it remains registered.
Successful creation restores demand; recovery-only resets preserve it.
With transfer-on-recreate enabled, an invalid old subscription
falls back to recreation. A
managed-session channel deadline
cancels recovery and hands control to the outer reconnect policy. After expiry,
any replacement attempt still waits for cancelled Publish attempts to roll back
their acknowledgements and release their active counts before replacing session
and subscription state.
Triggering (SetTriggering)
Triggering (OPC UA Part 4 §5.13.5) links a triggering monitored
item to one or more triggered items. When the triggering item fires
a notification, the triggered items' queued notifications are
reported in the next publish even if their monitoring mode is
Sampling (which would otherwise suppress reporting). This is the
canonical pattern for "sample many items at high rate, report on
demand". See Part 4 §5.13.1.6 for the full triggering model.
Aggregate-filtered monitored items follow these same monitoring-mode rules
(Part 4 5.13.1.3). Completion of an aggregate interval does not enable reporting
for a Disabled item or an untriggered Sampling item. A legitimately triggered
Sampling item can publish its queued aggregates; after that trigger is consumed,
interval completion alone does not cause another report.
The V2 engine exposes triggering through a hybrid API:
- Declarative — set
MonitoredItemOptions.TriggeredByNameswhen the item is added. - Imperative — call
ISubscription.SetTriggeringAsync(IMonitoredItem triggeringItem, add, remove, ct)at any time.
Both paths flow through the same batched apply pipeline: multiple
operations targeting the same triggering item collapse into a single
SetTriggering request carrying both the merged linksToAdd and
linksToRemove lists. Per Part 4 §5.13.5.2 the server processes
linksToRemove before linksToAdd, which matches the engine's
last-intent-wins conflict resolution.
The V2 engine models the topology as a per-item desired state:
each monitored item carries a list of stable triggering-item names
(DesiredTriggeredByNames) that reflects what the caller wants. The
engine reconciles desired state against the server via SetTriggering
requests whenever:
- An options change pushes a different
TriggeredByNamesvalue. - The imperative API mutates the desired set.
- An item is
Reset(recreate scenario) — the engine replays the desired set so transient server-side state matches the durable client-side intent.
The OPC UA spec allows a triggered item to be linked to multiple
triggering items (N:M); the V2 API exposes this directly via the
plural TriggeringItems / TriggeredItems projections.
Declarative triggering
The simplest way to declare triggering is via MonitoredItemOptions
at item-add time:
ManagedSession session = await new ManagedSessionBuilder(config, telemetry)
.UseEndpoint(endpoint)
.ConnectAsync(ct);
ISubscription sub = session.AddSubscription(handler, new SubscriptionOptions
{
PublishingInterval = TimeSpan.FromSeconds(1)
});
// Triggering item — reports normally at its sampling interval.
sub.TryAddMonitoredItem("trig",
VariableIds.Server_ServerStatus_CurrentTime,
o => o with { MonitoringMode = MonitoringMode.Reporting },
out _);
// Triggered item — samples in the background; only reports when
// "trig" reports.
sub.TryAddMonitoredItem("sensor",
new NodeId("Sensor1", 2),
o => o with
{
MonitoringMode = MonitoringMode.Sampling,
TriggeredByNames = ["trig"]
},
out _);
The engine batches the underlying CreateMonitoredItems /
SetTriggering requests and applies them on the next subscription
apply pass. There is no need to explicitly call any method to
"finish" the triggering setup — once both items are Created, the
engine issues the SetTriggering call automatically.
Order of TryAddMonitoredItem calls does not matter; the engine
will keep the triggering operation queued until both items are
created on the server, then issue the request.
Imperative triggering
Mutate triggering relationships at any time after items exist via
SetTriggeringAsync:
SetTriggeringResult result = await sub.SetTriggeringAsync(
triggeringItem: trig,
linksToAdd: [sensor1, sensor2],
linksToRemove: null,
ct: ct);
foreach ((IMonitoredItem item, StatusCode status) in result.AddResults)
{
if (!StatusCode.IsGood(status))
{
// BadMonitoredItemIdInvalid, BadInvalidState, etc.
}
}
The call queues a single TriggeringOperation and returns a
ValueTask that completes when the next apply pass applies it. The
result's per-link entries are in the same order as the input lists
for easy pairing.
Convenience overloads use stable monitored-item names:
await sub.SetTriggeringAsync("trig", "sensor1", "sensor2");
// add + remove in one call (server processes remove before add per §5.13.5.2):
await sub.SetTriggeringAsync(
"trig",
add: ["sensor3"],
remove: ["sensor1"],
ct: ct);
Unknown names throw ArgumentException synchronously.
Cancellation semantics
The CancellationToken passed to SetTriggeringAsync controls the await and marks the queued operation as cancelled on a best-effort basis:
- Cancelling the token aborts the await and surfaces an
OperationCanceledExceptionto the caller. - The engine attempts to skip the queued operation on the next apply pass. If cancellation fires before the apply pass picks the op off the queue, the server-side
SetTriggeringrequest is NOT issued for this op. - This is best effort only: if the apply pass has already begun dispatching the RPC for the op's group, the server-side mutation cannot be cancelled — the in-flight RPC completes regardless.
- The desired-state mutations performed synchronously by the engine before the await (the updates that make
IMonitoredItem.TriggeringItems/IMonitoredItem.TriggeredItemsand any subsequent snapshot reflect the new topology) already happened whenSetTriggeringAsyncreturned itsValueTask. They stand regardless of cancellation. - To revert local intent, the caller must explicitly issue an opposing
SetTriggeringAsync(or change the declarativeMonitoredItemOptions.TriggeredByNames).
Warning
Cancelling the
CancellationTokencannot guarantee the server-sideSetTriggeringcall is skipped — it is best-effort; an op that has already begun its server request will still complete server-side, and local desired-state is never rolled back automatically.
// Original intent: when "trig" fires, also report "sensor1" and "sensor2".
await sub.SetTriggeringAsync("trig", "sensor1", "sensor2");
// To undo, issue an opposing call with the items in `remove`. Note that
// even if the first call's cancellation token had fired, the server
// might still have applied the link (race with the apply pass) and the
// local desired-state intent would have stood — so an explicit opposing
// call is the only reliable revert path.
await sub.SetTriggeringAsync(
"trig",
add: null,
remove: ["sensor1", "sensor2"],
ct: ct);
N:M relationships
A triggered item may be linked to many triggering items, and a
triggering item may have many triggered items. Use multiple
SetTriggeringAsync calls (or include the same triggered name under
multiple triggers' TriggeredByNames):
sub.TryAddMonitoredItem("trigA", ..., out var trigA);
sub.TryAddMonitoredItem("trigB", ..., out var trigB);
sub.TryAddMonitoredItem("shared",
nodeId,
o => o with
{
MonitoringMode = MonitoringMode.Sampling,
TriggeredByNames = ["trigA", "trigB"]
},
out var shared);
// "shared" reports whenever EITHER trigA OR trigB fires:
Assert.That(shared.TriggeringItems, Is.EquivalentTo(new[] { trigA, trigB }));
Assert.That(trigA.TriggeredItems, Has.Member(shared));
Assert.That(trigB.TriggeredItems, Has.Member(shared));
TriggeringItems and TriggeredItems are read-only projections
resolved on demand against the subscription's monitored-item
collection. They reflect the desired topology (intent) — so they
work immediately on TryAdd before any request fires, and survive
restore-from-snapshot without depending on server state.
Save / load / restore behavior
The triggering topology round-trips through the V2 snapshot path:
MonitoredItemStateSnapshot.TriggeredByNamescaptures the runtime desired state at snapshot time.SubscriptionManager.SaveAsync/LoadAsync(and the in-memorySnapshotSubscriptions/RestoreSubscriptionsAsyncextensions) persist this field via the standard binary encoder.
On load, the engine takes one of three paths:
| Scenario | Behavior |
|---|---|
| TransferSubscriptions success | Local desired state is restored from the snapshot. NO SetTriggering request is issued — per Part 4 §5.13.5 conformant servers preserve server-side triggering relationships across a session transfer. |
| Recreate-fallback (transfer rejected or unsupported) | Items reset to "not created"; the saved DesiredTriggeredByNames is preserved on each item; the batched apply pass replays SetTriggering after items finish re-creating. |
In-session RecreateAsync (forced recreate) |
Same as recreate-fallback — desired state preserved through reset, replayed after re-creation. |
This closes the gap from issue
#3834:
triggering links are now automatically restored on
TransferSubscriptions and on recreate/reconnect; no manual
re-issue of SetTriggering is required by callers.
If a server fails to preserve links across transfer (contrary to the
spec), the V2 client view will indicate the links exist while
server-side notifications stop firing. Callers detecting this can
manually re-issue Subscription.SetTriggeringAsync per relationship.
Error handling
Per Part 4 §5.13.5.4 (Table 74) the only spec-specific per-link status
code is Bad_MonitoredItemIdInvalid. Service-level codes (Table 73)
include Bad_NothingToDo, Bad_TooManyOperations, and
Bad_SubscriptionIdInvalid.
The engine handles these as follows:
| Condition | Engine response |
|---|---|
Per-link Bad_MonitoredItemIdInvalid on add |
Surfaced via the returned SetTriggeringResult.AddResults[i].Status; the triggered item's desired-state entry for that triggering name is rolled back so it matches reality. |
Per-link Bad on remove |
Surfaced via RemoveResults[i].Status; the desired-state entry is re-added so the snapshot continues to reflect the still-existing server link. |
Service-level Bad_SubscriptionIdInvalid |
Operations are re-queued (not failed terminally); they replay after the subscription state machine recreates the subscription. |
Service-level Bad_TooManyOperations |
Surfaced as a fatal ServiceResultException on all contributing TCSs. Callers wishing to recover should chunk their SetTriggeringAsync calls manually; auto-chunking is a planned follow-up. |
| Communication errors (timeout, channel closed) | Routed through the existing retry policy; bounded by MaxTriggeringRetryCount to prevent infinite loops. |
Triggering item never reaches Created |
After MaxTriggeringRetryCount re-queues, the operation completes with the triggering item's propagated error status (or Bad_MonitoredItemIdInvalid as a fallback). |
Unbounded monitored items
The V2 subscription engine
(Opc.Ua.Client.Subscriptions.ISubscription, returned from
session.TryGetSubscriptionManager(out var manager) then manager.Add(...))
lets a single logical
subscription hold an effectively unlimited number of monitored items.
When the per-subscription cap (MaxMonitoredItemsPerSubscription from
the server's capabilities, OPC UA Part 4 §5.13.2) would be exceeded,
the engine transparently splits monitored items across additional
server-side partition subscriptions and presents one logical
collection to the caller. Single-partition workloads (the common
case) keep their pre-existing fast path; partitioning kicks in only
when needed.
How it works
-
ISubscriptionManager.Add(handler, options)returns aLogicalSubscriptionwrapper that implementsISubscriptionandIPartitionedSubscription. Pattern-match on the latter to introspect the partition layout:ISubscription subscription = session.SubscriptionManager.Add(handler, optionsMonitor); if (subscription is IPartitionedSubscription partitioned) { Console.WriteLine($"Spread over {partitioned.PartitionCount} partition(s)"); foreach (uint partitionId in partitioned.PartitionIds) { Console.WriteLine($" partition server id: {partitionId}"); } } -
ISubscription.MonitoredItemsis backed by a composite collection that aggregates every partition's items behind oneIMonitoredItemCollection.TryAdd/TryRemove/TryGetMonitoredItemByName/TryGetMonitoredItemByClientHandleenumerate every partition; the caller never needs to know which partition owns which item. -
When the placement policy decides a new partition is needed, the engine constructs a sibling server-side subscription using the same
SubscriptionOptionsand the same notification handler. The new partition is registered in the manager's publish-dispatch registry so publish responses route to it like any other subscription. -
ISubscriptionNotificationHandlercallbacks always receive the logical wrapper as theISubscription subscriptionparameter. When more than one partition is active the engine serialises calls through a per-wrapper semaphore so consumers observe one handler invocation at a time, matching the single-partition behaviour they came to rely on under V2. -
Notifications include the source partition's server-side id via the
PartitionServerIdfield onDataValueChangeandEventNotification. Sequence numbers stay per-partition ((PartitionServerId, sequenceNumber)disambiguates across partitions).
Affinity — pinning items to the same partition
OPC UA SetTriggering is scoped to one server-side subscription
(Part 4 §5.13.6). Items that need to participate in a triggering
relationship (or any other per-subscription feature) must land in the
same partition. Pin them via
MonitoredItemOptions.Affinity:
var optionsMonitor = new OptionsMonitor<MonitoredItemOptions>(new MonitoredItemOptions
{
StartNodeId = new NodeId("MyVariable", 2),
SamplingInterval = TimeSpan.FromMilliseconds(500),
Affinity = "alarms-group" // every item with this tag stays together
});
subscription.MonitoredItems.TryAdd("MyItem", optionsMonitor, out _);
- Items with the same non-null
Affinityvalue are guaranteed to share a partition. - Once the partition reaches the per-partition cap the next
TryAddwith the same tag returnsfalse— the contract is strict so the group never splits. Callers must shrink the group, raiseMaxMonitoredItemsPerPartition, or pick a different tag. null(the default) places no co-location constraint; items without affinity fill partitions first-fit.
LogicalSubscription.SetTriggeringAsync(triggering, linksToAdd, linksToRemove) validates that every linked item shares the same
partition as the triggering item and throws ArgumentException
otherwise. The exception message points callers at Affinity for
remediation.
Configuration
All knobs live on SubscriptionOptions:
| Property | Default | Effect |
|---|---|---|
DisableUnboundedItemMode |
false |
When true, the wrapper is bound to one server-side subscription; TryAdd calls beyond the server cap surface Bad_TooManyMonitoredItems per-item like the pre-V2 engine. |
MaxMonitoredItemsPerPartition |
null |
Per-partition upper bound. null means "let the reactive fallback discover the server's effective cap". Set to a smaller value to keep partitions small for snapshot/transfer scaling, or to a larger value to override an artificially low server limit. |
SecondaryPartitionIdleTimeout |
30s |
Idle timeout after which an empty secondary partition is deleted from the server. The primary partition is never deleted while the logical subscription is alive so the wrapper's server-side identifier stays stable. Set to TimeSpan.Zero for immediate delete; set to Timeout.InfiniteTimeSpan to disable idle-delete. |
The reactive cap fallback is always on whenever
DisableUnboundedItemMode is false: the engine watches every
CreateMonitoredItems response and, on the first
Bad_TooManyMonitoredItems outcome, marks the offending partition
no-grow so subsequent placements fan out to a new partition. This
handles servers whose actual limit is lower than the advertised
capability and servers whose limit changes between session lifetimes.
Snapshot, save / load, and transfer
Multi-partition logical subscriptions snapshot every partition. The capture path is:
LogicalSubscription.SnapshotAllPartitions()returnsIReadOnlyList<SubscriptionStateSnapshot>— one snapshot per partition, ordered primary-first.- Every snapshot in the list carries the wrapper's stable
LogicalGroupId(a lazy-generated GUID cached for the lifetime of the wrapper) and an incrementingPartitionIndex(0for the primary,1+for secondaries in mint order). ManagedSession.SnapshotSubscriptions()andISubscriptionManager.SaveAsync(...)flatten across partitions automatically, so callers persisting the list see the full state.- Single-partition wrappers continue to emit exactly one snapshot.
Old V1 snapshot files have
LogicalGroupId == nulland load via the standalone path unchanged.
The restore path:
ISubscriptionManager.LoadAsync(...)andManagedSession.RestoreSubscriptionsAsync(...)group incoming snapshots byLogicalGroupId. Snapshots with anullgroup restore as standalone subscriptions; non-null groups become one multi-partitionLogicalSubscriptionwrapper viaSubscriptionManager.RestoreGroupAsync(...)(internal).- Restored secondary partitions go through a new internal
LogicalSubscription.AppendPreloadedPartition(...)hook so the composite collection's placement policy + idle-delete timer + (if applicable) durable hook are wired exactly as if the partition had been minted on demand. - When
transferSubscriptions: trueis passed, each partition's saved server-side id is preserved viaTransferSubscriptions; partitions whose transfer fails fall back to recreate. - Strict grouping is enforced: a non-null
LogicalGroupIdmust appear on a contiguous0..N-1sequence ofPartitionIndexvalues with no duplicates and exactly one primary. Malformed snapshot groups throwServiceResultException(BadDecodingError)naming the offendingLogicalGroupId— a corrupt or hand-edited snapshot fails loudly rather than silently fragmenting state.
MonitoredItemStateSnapshot.Affinity round-trips so restored
subscriptions regroup items into the same affinity-pinned partition
the source had.
Republishing retained notifications and requesting initial values are independent.
If an origin session disconnects before acknowledging a message, a transfer can
recover that message from the server's retransmission queue. With
SendInitialValuesOnTransfer also enabled, the target can receive the same static
value again in a new notification message. Distinguish these batches by their
sequence numbers, not by value equality. On the classic API, retransmission is
controlled by RepublishAfterTransfer, while initial values are requested with
the transfer call's sendInitialValues argument. Deferring acknowledgements
retains messages for explicit Republish requests; it does not ask the server
to resend them unsolicited. See
OPC UA Part 4, TransferSubscriptions.
The classic client acknowledges messages selected for replay only after receiving
them. Messages not selected for replay are acknowledged when transfer completes;
the advertised available-sequence list remains intact.
Durable subscriptions
The server converts the configured durable lifetime in hours to milliseconds before revising keep-alive and lifetime counts. The conversion uses wide arithmetic, including lifetimes longer than the UInt32 millisecond range.
SetAsDurableAsync(lifetime) records the durable intent on the
wrapper and applies it synchronously to every partition that is
already Created (it returns the minimum revised lifetime across
those partitions). For partitions that have not yet completed
their initial CreateSubscription — both the primary on a brand
new subscription and any future secondary minted by the placement
policy under capacity pressure — the wrapper installs an
OnAfterCreateAsync hook on the partition's state machine. The
state machine awaits the hook exactly once between
CreateSubscription and the first CreateMonitoredItems,
satisfying the OPC UA Part 4 §5.13.9 ordering rule that
SetSubscriptionDurable must precede any monitored-item creation.
The hook is cleared after invocation; the wrapper re-installs it on
each SetAsDurableAsync call so it survives reconnect / recreate
cycles. Hook failures are logged as a warning and surfaced via
SubscriptionState.Modified rather than tearing the partition
down.
Performance
Single-partition workloads observe no overhead from the wrapper — the composite collection short-circuits to the primary's own collection without taking any extra locks or building indexes. Multi-partition workloads pay:
- One semaphore acquire/release per notification callback (small).
- O(P) partition scans for
TryGetMonitoredItemByName/TryGetMonitoredItemByClientHandlemisses against the composite index (P is typically single-digit). - One extra
Subscriptioninstance per partition (each holds its own state machine, ack queue position, and notification pipeline).
Limitations and roadmap
Cross-partition SetTriggering is rejected by design: per OPC UA
Part 4 §5.13.6 the service is scoped to a single server-side
subscription, and re-grouping already-placed items would require
delete + recreate (losing per-item server ids and briefly stopping
publishing). Plan Affinity up-front for items that need to
participate in a triggering relationship; the engine will keep the
group co-located for the lifetime of the wrapper.
This is the only multi-partition feature gap — single-partition workloads cover the vast majority of OPC UA client use cases unchanged.
Streaming subscriptions
IStreamingSubscription exposes OPC UA subscription notifications as
IAsyncEnumerable<T> streams. Each SubscribeXxxAsync call adds a
monitored item to a shared, lazy-created OPC UA subscription and pipes
notifications through a System.Threading.Channels.Channel<T>.
Disposing the enumerator removes the monitored item.
This API sits on top of the V2 subscription engine
(src/Opc.Ua.Client/Subscription). It is not a replacement
for either the classic or V2 callback-based API — it is a thin
abstraction targeted at three concrete client scenarios:
- State-machine waits — "subscribe, observe transitions until X, unsubscribe".
- Short-lived monitoring — "I need a sample for 30 seconds".
- Typed alarm streaming — Part 9 alarm records via
AlarmStreamExtensions(see AlarmsAndConditions.md).
For long-lived application subscriptions, the callback-based
ISubscriptionManager.Add + ISubscriptionNotificationHandler API
remains the right choice (see
Sessions.md §4.2 DefaultSubscriptionEngine (V2)).
Obtaining an IStreamingSubscription
ManagedSession.DefaultStreaming lazily constructs a shared instance
the first time it is accessed and disposes it when the session is
disposed.
ManagedSession session = await new ManagedSessionBuilder(configuration, telemetry)
.UseEndpoint(endpoint)
.ConnectAsync(ct);
IStreamingSubscription streaming = session.DefaultStreaming;
If you need to bind to a specific ISubscriptionManager (for example
in tests or with the raw Session's V2 engine), construct directly:
var streaming = new StreamingSubscription(
subscriptionManager: session.SubscriptionManager,
subscriptionOptions: new SubscriptionOptions
{
PublishingInterval = TimeSpan.FromMilliseconds(250),
KeepAliveCount = 10,
LifetimeCount = 100,
});
The underlying OPC UA subscription is not created until the first
SubscribeXxxAsync call. Once created it is shared by every active
SubscribeXxxAsync enumerator on this StreamingSubscription.
Subscribing to data changes
await foreach (DataValueChange change in streaming
.SubscribeDataChangesAsync(VariableIds.Server_ServerStatus_CurrentTime, ct: ct)
.ConfigureAwait(false))
{
Console.WriteLine($"{change.MonitoredItem?.Name}: {change.Value}");
}
For multiple variables in a single stream:
var nodes = new[]
{
VariableIds.Server_ServerStatus_CurrentTime,
VariableIds.Server_ServerStatus_SecondsTillShutdown,
};
await foreach (DataValueChange change in streaming
.SubscribeDataChangesAsync(nodes, options: new MonitoredItemOptions
{
SamplingInterval = TimeSpan.FromMilliseconds(500),
QueueSize = 5,
}, ct: ct).ConfigureAwait(false))
{
Console.WriteLine($"{change.MonitoredItem?.ClientHandle}: {change.Value}");
}
Each MonitoredItemOptions is treated as a template; only StartNodeId
is overridden internally per node.
Subscribing to events
EventFilter filter = new AlarmEventFilterBuilder()
.ForAlarms()
.Build();
await foreach (EventNotification evt in streaming
.SubscribeEventsAsync(ObjectIds.Server, filter, ct: ct)
.ConfigureAwait(false))
{
// Raw access; for typed records use SubscribeAlarmsAsync.
Console.WriteLine($"#{evt.Fields.Count} fields");
}
SubscribeEventsAsync does not validate the filter. Use
AlarmEventFilterBuilder for Part 9 events and any custom
SimpleAttributeOperand-based filter for other event types.
Composing streams
StreamingSubscriptionExtensions ships four LINQ-style helpers
designed for the bounded-observation use cases. They wrap the source
IAsyncEnumerable<T> and stop iterating (which disposes the
underlying enumerator and the monitored item) when their condition
fires.
// 1) Wait until a predicate matches, then return the matching item.
DataValueChange completed = await streaming
.SubscribeDataChangesAsync(buildProgressVariable)
.TakeUntilAsync(c => (double)c.Value.Value >= 100.0)
.LastAsync(ct);
// 2) Cap by wall-clock time. Completes silently when the timeout elapses.
List<DataValueChange> samples = await streaming
.SubscribeDataChangesAsync(sensor)
.WithTimeoutAsync(TimeSpan.FromSeconds(30))
.ToListAsync(ct);
// 3) Take exactly N values.
List<DataValueChange> firstThree = await streaming
.SubscribeDataChangesAsync(sensor)
.TakeAsync(3)
.ToListAsync(ct);
// 4) Buffer N items into a list — for one-shot snapshots.
IReadOnlyList<DataValueChange> snapshot = await streaming
.SubscribeDataChangesAsync(sensor)
.BufferedAsync(count: 10, ct);
TakeUntilAsync yields the matching item last, so callers can grab
the transition value with LastAsync / a terminating handler.
Lifecycle, cancellation, disposal
Each stream has a bounded local buffer, including the default data-change
subscription. Its capacity is max(1, QueueSize) * monitoredItemCount, capped
at int.MaxValue; event streams default to ten entries per monitored item.
When full, DiscardOldest chooses between evicting the oldest buffered entry
and discarding the incoming entry. StreamingSubscription.DroppedNotificationCount
reports the cumulative local drops across data-change and event streams.
For a multi-node stream, this is one shared queue, not a per-node allocation.
With DiscardOldest enabled, a busy node can evict a quiet node's only queued
value. There is no local guarantee that each node's latest value remains buffered,
and overflow increments the drop counter rather than failing the stream. Use
separate single-node streams, consumed independently, when per-node retention is
required. Server-side per-monitored-item queues do not change this local policy.
The streaming subscription guarantees three invariants:
- Lazy subscription creation. No OPC UA
CreateSubscriptionround-trip happens until your firstSubscribeXxxAsynccall. - Reference-counted monitored items. Each call adds a monitored
item; disposing the enumerator (end of the
await foreach, an exception, or explicitawait using) removes that monitored item. The underlying subscription stays alive for other enumerators. - Disposal order. Disposing the
StreamingSubscriptioncompletes all open channels and attempts to delete the underlying OPC UA subscription. Disposing theManagedSessioncalls this for you.
V2 subscription disposal gives each server-side delete a separate five-second cancellation deadline. Local cleanup does not wait indefinitely for an unavailable server. A failed or timed-out delete is logged; it does not prove remote deletion, and the server may retain the subscription until its configured lifetime expires.
Publish workers survive recovery for subscriptions that the V2 engine actually created. A never-created subscription does not inherit worker retention from a classic subscription or a V2 subscription that has already been removed. An intentionally disabled or deleted subscription likewise contributes no retained demand until it is created again.
Cancellation propagates the natural way: pass a CancellationToken to
SubscribeXxxAsync or the outer await foreach (via
WithCancellation). When the token fires the enumerator stops, the
finally block removes the monitored item, and the loop body throws
OperationCanceledException.
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(2));
try
{
await foreach (DataValueChange change in
streaming.SubscribeDataChangesAsync(sensor, ct: cts.Token))
{
Process(change);
}
}
catch (OperationCanceledException) { /* expected */ }
Pairing with AlarmClient
The streaming subscription and AlarmClient are complementary:
IStreamingSubscriptiondelivers the events (raw or typed).AlarmClientcalls the methods (acknowledge, shelve, suppress, reset, etc.).
AlarmClient alarms = session.GetAlarmClient();
IStreamingSubscription streaming = session.DefaultStreaming;
await foreach (ConditionTypeRecord rec in streaming
.SubscribeAlarmsAsync(ObjectIds.Server)
.TakeUntilAsync(r =>
r is AlarmConditionTypeRecord a &&
a.ConditionId == myAlarmId &&
a.ActiveStateId == true))
{
if (rec is AlarmConditionTypeRecord active && active.ActiveStateId == true)
{
await alarms.AcknowledgeAsync(
active.ConditionId,
active.EventId,
new LocalizedText("en", "Auto-acked")).ConfigureAwait(false);
}
}
See AlarmsAndConditions.md for the typed record hierarchy.
Classic → V2 surface mapping
This section is the working reference for porting classic
(Opc.Ua.Client.Subscription / Opc.Ua.Client.MonitoredItem) code to
the V2 surface (Opc.Ua.Client.Subscriptions.ISubscription /
Opc.Ua.Client.Subscriptions.MonitoredItems.IMonitoredItem). The
tables describe today's APIs side-by-side; "not on V2" rows record
behaviour the V2 engine replaces by design (handler-centric,
channel-based pipeline, snapshot/restore, options-monitor-driven
reconciliation, etc.) along with the recommended V2 alternative.
Subscription lifecycle
| Classic | V2 |
|---|---|
new Subscription(template) + Session.AddSubscription(s) + s.CreateAsync() |
ISubscriptionManager.Add(handler, IOptionsMonitor<SubscriptionOptions>) — V2 creates the subscription on the server asynchronously; callers poll subscription.Created (or attach an OnSubscriptionStateChangedAsync handler). |
Session.RemoveSubscriptionAsync(s) |
await subscription.DisposeAsync() — V2 removal is dispose-on-subscription. |
s.CreateAsync(ct) / s.ModifyAsync(ct) / s.DeleteAsync(silent, ct) |
Implicit via Add / options push / DisposeAsync. No explicit V2 calls — behaviour is driven by options + lifecycle. |
s.SetPublishingModeAsync(bool, ct) |
Push SubscriptionOptions { PublishingEnabled = ... } via the IOptionsMonitor<SubscriptionOptions>. The V2 manager picks up the change automatically. |
s.ChangesPending / s.ChangesCompleted() |
Not on V2 (the engine is fully push-driven; no "pending changes" concept). Callers wait on the side-effect (e.g. IMonitoredItem.Created, options-monitor change tokens). |
Notifications and callbacks
| Classic | V2 |
|---|---|
s.FastDataChangeCallback (delegate) |
ISubscriptionNotificationHandler.OnDataChangeNotificationAsync(...) |
s.FastKeepAliveCallback (delegate) |
ISubscriptionNotificationHandler.OnKeepAliveNotificationAsync(...) |
s.FastEventCallback |
ISubscriptionNotificationHandler.OnEventDataNotificationAsync(...) |
item.Notification += handler (per-item event) |
Per-item dispatch through the handler with DataValueChange.MonitoredItem to identify the source. |
s.PublishStatusChanged / s.StateChanged events |
Unified into a single callback ISubscriptionNotificationHandler.OnSubscriptionStateChangedAsync(ISubscription, SubscriptionState, PublishState, CancellationToken) that surfaces lifecycle (Opened / Created / Modified / Deleted) and publish-state (Republish / Recovered / Transferred) transitions. |
item.DequeueValues() (client-side cache) |
Not on V2 — values stream into the handler. The handler is the cache; callers retain whatever they need. |
s.LastNotification / s.Notifications / s.LastNotificationTime |
Not on ISubscription. The manager exposes MissingMessageCount / RepublishMessageCount; handlers maintain their own derived state (e.g. via the publishTime arg on each callback). |
s.PublishingStopped |
Not exposed as a property. Handlers derive it from OnSubscriptionStateChangedAsync (the PublishState mask flips between Republish / Recovered / Transferred). |
Subscription-level service operations
| Classic | V2 |
|---|---|
s.RepublishAsync(seq, ct) |
Not on V2. The V2 engine auto-republishes on gap detection via MessageProcessor.TryRepublishAsync; there is no user-driven variant. Callers needing raw access can call session.RepublishAsync(null, subscriptionId, seq, ct). |
s.ResendDataAsync(ct) |
Not on V2. Callers needing raw access call session.CallAsync(null, ResendData methodId, ...). |
s.ConditionRefreshAsync(ct) |
s.ConditionRefreshAsync(ct) — same shape. |
s.ConditionRefresh2Async(monitoredItemId, ct) |
item.ConditionRefreshAsync(ct) on IMonitoredItem (per-item; no monitoredItemId arg needed). |
s.SetTriggeringAsync(triggering, links, removes, ct) returning SetTriggeringResponse |
ISubscription.SetTriggeringAsync(IMonitoredItem triggeringItem, IReadOnlyCollection<IMonitoredItem>? linksToAdd, IReadOnlyCollection<IMonitoredItem>? linksToRemove, CancellationToken ct) returning SetTriggeringResult with per-link statuses; plus name-based fluent overloads; plus the declarative MonitoredItemOptions.TriggeredByNames option (see Triggering). Supports N:M via IMonitoredItem.TriggeringItems plural; batches per-triggering-item requests; replays automatically on recreate/reconnect. |
s.TransferAsync(target, sendInitialValues, ct) |
Configure transfer-on-recreate via ManagedSessionBuilder.WithTransferSubscriptionsOnRecreate(true). The per-call sendInitialValues toggle lives on SubscriptionOptions.SendInitialValuesOnTransfer (default false). |
s.SetSubscriptionDurableAsync(...) |
ISubscription.SetAsDurableAsync(TimeSpan lifetime, CancellationToken ct = default) → revised lifetime hours. |
s.SaveMessageInCache(...) |
Not on V2 (classic internal). The V2 message pipeline is channel-based with no replay cache. |
Monitored-item management
| Classic | V2 |
|---|---|
s.AddItem(item) / s.AddItems(IEnumerable) |
s.MonitoredItems.TryAdd(name, IOptionsMonitor<MonitoredItemOptions>, out IMonitoredItem) — V2 keys items by a caller-supplied stable string name. Fluent helper: s.TryAddMonitoredItem(name, nodeId, configure, out _). |
s.RemoveItem(item) / s.RemoveItems(...) |
s.MonitoredItems.TryRemove(clientHandle). |
s.ApplyChangesAsync(ct) |
Not needed — V2 batches automatically via the options monitor. |
s.CreateItemsAsync(ct) / s.ModifyItemsAsync(ct) / s.DeleteItemsAsync(...) |
Implicit via TryAdd / options push / TryRemove. |
s.SetMonitoringModeAsync(mode, ids, ct) |
Push MonitoredItemOptions { MonitoringMode = ... } per item. |
s.ResolveItemNodeIdsAsync(ct) |
Not on V2 — callers resolve RelativePath to NodeId ahead of time via Browse / TranslateBrowsePathsToNodeIds. |
s.MonitoredItems / s.MonitoredItemCount |
s.MonitoredItems.Items / s.MonitoredItems.Count. |
Per-item runtime
| Classic | V2 |
|---|---|
item.ClientHandle |
IMonitoredItem.ClientHandle. |
item.ServerId |
IMonitoredItem.ServerId. |
item.Status.Error / item.Status.Created / item.Status.Id |
IMonitoredItem.Error / Created / ServerId. |
item.AttributesModified |
Not on V2 — reconciliation is driven by IOptionsMonitor<MonitoredItemOptions> change tokens; there is no "modified" flag to query. |
item.Filter round-trip |
IMonitoredItem.FilterResult. |
item.DequeueValues() / item.LastValue |
Not on V2 — values flow through ISubscriptionNotificationHandler.OnDataChangeNotificationAsync(...); the handler decides what to retain. |
item.Notification += ... (event) |
Per-item dispatch through OnDataChangeNotificationAsync with DataValueChange.MonitoredItem. |
item.GetEventTypeAsync / GetFieldValue / GetEventTime / GetFieldName |
Not on V2 IMonitoredItem — event-field helpers are caller-side. For typed Part 9 alarm records use AlarmStreamExtensions.SubscribeAlarmsAsync. |
item.TriggeringItemId / item.TriggeredItems (1:1) |
IMonitoredItem.TriggeringItems (plural, N:M) and IMonitoredItem.TriggeredItems (reverse "items I trigger") — both on-demand projections by stable name. Matches OPC UA Part 4 §5.13.5 N:M; runtime desired-state mutations from imperative SetTriggeringAsync are immediately visible. |
Persistence (save / load)
| Classic | V2 |
|---|---|
session.Save(Stream, IEnumerable<Subscription>) (BinaryEncoder + SubscriptionState.Encode) |
ISubscriptionManager.SaveAsync(Stream, IServiceMessageContext, IEnumerable<ISubscription>?, CancellationToken), with fluent ManagedSession.SaveSubscriptionsAsync(stream) extension. |
session.Load(Stream, bool transferSubscriptions) |
ISubscriptionManager.LoadAsync(Stream, IServiceMessageContext, handlerFactory, transferSubscriptions, CancellationToken), with fluent ManagedSession.LoadSubscriptionsAsync(stream, factory, transfer, ct). Recreate (false) and transfer (true via TransferSubscriptions; falls back to recreate on Bad_SubscriptionIdInvalid / Bad_ServiceUnsupported) both work end-to-end. |
s.Snapshot(out SubscriptionState) / s.Restore(SubscriptionState) |
ISubscription.Snapshot() → SubscriptionStateSnapshot; ISubscriptionManager.RestoreAsync(handler, state, transfer, ct); per-item IMonitoredItem.Snapshot() → MonitoredItemStateSnapshot. Fluent: ManagedSession.SnapshotSubscriptions() / RestoreSubscriptionsAsync(states, factory, transfer, ct). |
| Triggering survives save/load | Classic: MonitoredItemState.TriggeredItems (server-id based, 1:1). V2: MonitoredItemStateSnapshot.TriggeredByNames (name based, N:M; round-trips through the binary encoder; replays automatically on recreate, see Save / load / restore behavior). |
Tuning knobs
| Classic | V2 |
|---|---|
s.MaxMessageCount |
Not on V2 — the channel-based pipeline uses an unbounded queue with backpressure. |
s.MinLifetimeInterval (property) |
SubscriptionOptions.MinLifetimeInterval. |
s.DisableMonitoredItemCache |
Not on V2 — there is no per-item cache to disable (the handler is the cache). |
s.SequentialPublishing |
Always-on. The V2 prioritized publish-ack channel guarantees per-subscription in-order delivery; documented on ISubscriptionNotificationHandler. |
s.RepublishAfterTransfer |
Implicit and always-on; no opt-out. When TransferSubscriptions succeeds, the V2 engine immediately republishes every sequence number the server reports as still available in its retransmission queue (MessageProcessor.RecoverTransferredMessagesAsync), so a subscription that stays quiet - or only emits keep-alives - after the transfer still recovers the pending notifications. Gaps detected later are filled by MessageProcessor.TryRepublishAsync. |
s.OutstandingMessageWorkers (per-subscription) |
Manager-wide PublishWorkerCount. |
s.Id / s.TransferId |
ISubscription.ServerId (uint). |
s.Handle (caller bookkeeping) |
Not on ISubscription. Callers keep a side dictionary keyed by the item Name. |
Engine wiring
| Classic | V2 |
|---|---|
Session.SubscriptionEngineFactory defaulted to ClassicSubscriptionEngineFactory.Instance |
Defaulted to DefaultSubscriptionEngineFactory.Instance on ManagedSession. Raw Session constructed with DefaultSessionFactory defaults to classic for backwards compatibility; opt in by passing SubscriptionEngineFactory = DefaultSubscriptionEngineFactory.Instance. |
Session.AddSubscription(Subscription) (classic-typed) |
Unchanged — classic subscriptions are still added via this API on classic-engine sessions. On a V2-engine ManagedSession, classic subscriptions are bridged onto the V2 publish pipeline by an internal SubscriptionBridge. |
ISession.TryGetSubscriptionManager (V2) |
Returns the V2 manager alongside ManagedSession.Subscriptions (classic API), so both surfaces coexist on the same session. |
Per-item options mapping
Every classic configurable property maps directly to a field on
MonitoredItemOptions: StartNodeId, AttributeId, IndexRange,
Encoding, MonitoringMode, SamplingInterval, Filter,
QueueSize, DiscardOldest, TimestampsToReturn. The Order
and Name keys are V2-only (the latter is the dictionary key
used by IMonitoredItemCollection). item.RelativePath /
item.ResolveItemNodeIdsAsync / item.DisplayName are classic
caller conventions with no V2 equivalent — V2 uses a stable
per-item Name string instead.
Three-API summary
| Aspect | Classic Subscription |
V2 ISubscriptionManager |
IStreamingSubscription |
|---|---|---|---|
| Notification delivery | MonitoredItem.Notification event |
ISubscriptionNotificationHandler callback |
IAsyncEnumerable<T> |
| Add monitored item | subscription.AddItem(item); ApplyChanges() |
subscription.MonitoredItems.TryAdd(name, options, out _) |
streaming.SubscribeXxxAsync(...) |
| Remove monitored item | subscription.RemoveItem(item); ApplyChanges() |
subscription.MonitoredItems.TryRemove(handle) |
Dispose enumerator |
| Triggering API | SetTriggeringAsync(MonitoredItem, ArrayOf<MonitoredItem>, ArrayOf<MonitoredItem>, ct) (1:1 from triggered side via MonitoredItem.TriggeringItemId) |
SetTriggeringAsync(IMonitoredItem, IReadOnlyCollection<IMonitoredItem>?, IReadOnlyCollection<IMonitoredItem>?, ct) returning SetTriggeringResult; declarative MonitoredItemOptions.TriggeredByNames; N:M |
n/a (use the underlying V2 subscription) |
| Save / restore triggering | MonitoredItemState.TriggeredItems (server-id based) |
MonitoredItemStateSnapshot.TriggeredByNames (name based, N:M, round-trips through binary encoder) |
n/a |
| Reconnect / transfer triggering replay | RestoreTriggeringAsync re-issues SetTriggering after every reconnect |
TransferSubscriptions: no replay (server preserves links per spec); Recreate: automatic replay |
n/a |
| Cancellation | Manual | Per call (CT in handler) | Built-in (CT on stream) |
| Composition | Hand-rolled | Hand-rolled | LINQ-style helpers |
| Backpressure | Custom logic | Custom logic | Bounded channel internally |
| Best for | Legacy callers | Long-lived, multi-item subscriptions | Short-lived / wait-for-X scenarios |
All three APIs can coexist on the same session — pick the one that matches the use case.
Reference
- Subscription source:
src/Opc.Ua.Client/Subscription/ - Streaming source:
src/Opc.Ua.Client/Subscription/Streaming/ - Helpers:
src/Opc.Ua.Client/Subscription/Streaming/StreamingSubscriptionExtensions.cs - Alarm streaming:
src/Opc.Ua.Client/Alarms/AlarmStreamExtensions.cs - Sessions architecture and engine choice: Sessions.md
- Reference client sample:
samples/Reference/ConsoleReferenceClient/AlarmClientSample.cs