Files
UA-.NETStandard/docs/MigrationGuide.md
T
Marc Schier 46fa7d364a Harden recovery, concurrency, and resource lifetimes across the OPC UA stack (#4516)
# 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
2026-09-25 14:59:34 +00:00

1015 lines
43 KiB
Markdown

# Migration Guide
This document is the landing page for migrating your application between
versions of the OPC UA .NET Standard Stack. The detailed per-version
content lives in the [`migrate/`](migrate/) sub-folder; this page is the
index that points you at the right version folder and keeps cross-cutting
migration notes inline.
## General principles
1. All API that is replaced with newer API is marked `[Obsolete]` and
code should compile and work albeit of the warnings (which can be
suppressed). `[Obsolete]` API will be cleaned up in the next *minor*
version increment. We therefore recommend upgrading from minor
version to minor version and fixing all `[Obsolete]` warnings as you
go along.
2. API that cannot be supported anymore will be removed in a minor
version and migration steps documented in the version sub-folder.
We try to keep this to an absolute minimum.
3. Bugs or issues found in obsoleted API are not supported.
4. We follow semver, but do not use the major version indicator to
denote breaking changes like (1) or (2) as we should if we followed
related conventions. We are a small team and cannot afford to
maintain previous major versions, therefore we try to keep cases of
(2) to a minimum and expect you to upgrade to the next minor version
within 6 months of release.
> **Pro TIP.** Point your favourite coding agent at this guide and let
> it do the migration work for you. The
> [`opcua-v20-migration`](../.agents/skills/opcua-v20-migration/SKILL.md)
> agent skill knows when to load which sub-doc and runs the
> migration-analyzer codefixer end-to-end.
Copilot CLI discovers the skill automatically inside a clone. To install it
for use in any repository:
```bash
copilot plugin marketplace add OPCFoundation/UA-.NETStandard
copilot plugin install opcua-v20-migration@opcua-dotnet
```
## Per-version migration index
| From | To | Where to read |
| --- | --- | --- |
| `1.5.378` | `2.0.x` | [`migrate/2.0.x/`](migrate/2.0.x/README.md) — landing page and symptom-based thematic sub-doc index. |
| `1.05.377` | `1.05.378` | [§ inline below](#migrating-from-105377-to-105378) — small enough to keep on this page. |
| `1.04` | `1.05` | [§ inline below](#migrating-from-104-to-105) — small enough to keep on this page. |
Looking for the broader narrative (non-prescriptive overview of what
changed in a release)? See
[What's New in 2.0](WhatsNewIn2.0.md).
## Migrating code that used the exposed diagnostics locks
`IServerInternal`, `ISession` and `ISubscription` no longer expose their
synchronization primitives. The removed members are:
| Interface | Removed |
| --- | --- |
| `IServerInternal` | `DiagnosticsLock`, `DiagnosticsWriteLock` |
| `ISession` | `DiagnosticsLock` |
| `ISubscription` | `DiagnosticsLock`, `DiagnosticsWriteLock` |
A caller could not reason about these locks: it could not see what else took
them, in what order, or for how long, and holding one across a call back into
the stack could deadlock. Each owner now applies the mutation itself, so the
critical section stays inside the object that understands it.
```csharp
// was
lock (server.DiagnosticsLock)
{
server.ServerDiagnostics.RejectedSessionCount++;
}
// now
server.UpdateServerDiagnostics(diagnostics => diagnostics.RejectedSessionCount++);
```
The same shape applies to sessions and subscriptions:
```csharp
session.UpdateDiagnostics(diagnostics => diagnostics.ClientLastContactTime = now);
subscription.UpdateDiagnostics(diagnostics => diagnostics.NextSequenceNumber = next);
```
To read a value derived from the session or subscription diagnostics, use the
read counterpart, which holds the same lock for the duration of the projection:
```csharp
uint count = session.ReadDiagnostics(diagnostics => diagnostics.RepublishRequestCount);
```
**Do not let the diagnostics object escape the callback.** Once the callback
returns the lock is released, so any field read from a captured reference is
unsynchronized. Project the values you need inside the callback and return
those.
`IServerInternal.ServerDiagnostics` was removed for the same reason: it handed
out the mutable structure that the lock protects. `UpdateServerDiagnostics` and
the diagnostic node manager are the supported paths.
Analyzer `UA0024` flags each removed member and names its replacement. It
reports rather than auto-fixes: turning a `lock` statement body into a lambda is
not a transformation that can be applied safely without understanding what the
body captures and returns.
### Why there is no `[Obsolete]` shim
Every other removal in this guide keeps an `[Obsolete]` member for a release.
These do not, and deliberately so. A lock is only useful if it is *the* lock the
owner takes. A shim would have to hand back either a lock nobody else takes -
silently turning a working critical section into no synchronization at all - or
the real lock, which is exactly the coupling being removed. A missing member is
a compile error the analyzer explains; a shim would be a race that shows up in
production. `ISession` and `ISubscription` are also implemented by downstream
code, and re-adding an interface member would break every implementer.
## Migrating code that used ILocalNode.DataLock
`ILocalNode.DataLock` (implemented by `Node`) was removed. It returned the node
instance itself, so `lock (node.DataLock)` was `lock (node)`: one lock shared
between the stack, the node and every caller, taken in an order none of them
could see.
```csharp
// was
lock (node.DataLock)
{
value = node.Value;
}
// now - the node guards its own state
value = node.Value;
```
If the surrounding operation has to stay atomic across several calls, take a
lock the calling component owns. Do not reach for one that is reachable from a
shared node. Analyzer `UA0025` flags the removed member.
## Migrating code that used BaseVariableValue.Lock
`BaseVariableValue.Lock` was removed, and the constructor now takes a
`System.Threading.Lock` instead of an `object`.
A derived value class - which is what the source generator emits for every
structure variable - synchronizes through the protected `EnterLock()` /
`ExitLock()` pair:
```csharp
EnterLock();
try
{
// read or write the value fields
}
finally
{
ExitLock();
}
```
A component that has to make its own state atomic with the value passes a lock
it already owns to the constructor and takes that one directly. This is how the
server keeps its status and its diagnostics mutually exclusive:
```csharp
private readonly Lock m_diagnosticsLock = new();
// the value is constructed with the lock its owner already holds elsewhere
m_status = new ServerStatusValue(statusNode, status, m_diagnosticsLock);
// so the owner synchronizes against the value without the value handing anything out
lock (m_diagnosticsLock)
{
...
}
```
Analyzer `UA0026` flags the removed member. Note that regenerating the model
sources with the 2.0 generator produces the `EnterLock()` / `ExitLock()` form
already, so this only affects hand-written derived value classes and callers.
## Migrating code that locked on a NodeState or a NodeBrowser
A `NodeState` guards its own attributes, children, notifiers and references, and
`NodeState.CreateBrowser` guards the browser it builds. Nothing in the stack
takes a lock on a node instance any more, so neither should a caller:
```csharp
// was — the node manager reached for the node's monitor from outside the node
lock (source)
{
browser = source.CreateBrowser(context, view, referenceType, includeSubtypes,
browseDirection, default, null, false);
}
// now
INodeBrowser browser = source.CreateBrowser(context, view, referenceType,
includeSubtypes, browseDirection, default, null, false);
```
`lock (node)` was also the only way to make a check-then-act pair atomic. Use
`NodeState.AddReferenceIfMissing` instead, which does the check and the insert
under the node's own lock:
```csharp
// was
lock (node)
{
if (!node.ReferenceExists(ReferenceTypeIds.HasNotifier, true, ObjectIds.Server))
{
node.AddReference(ReferenceTypeIds.HasNotifier, true, ObjectIds.Server);
}
}
// now
node.AddReferenceIfMissing(ReferenceTypeIds.HasNotifier, true, ObjectIds.Server);
```
`NodeBrowser.DataLock` is gone with it. A browser is **single-consumer**: it
belongs to whoever created it and performs no synchronization of its own. A
derived browser that took `DataLock` inside its `Next()` override drops the
`lock` statement and keeps the body. Where a browser genuinely outlives one
service call — the instance parked in a continuation point for `BrowseNext` —
its owner serializes it, as the stack does for its own continuation points.
A node type that overrides `CreateBrowser` and builds its own browser instead of
delegating to the base implementation must fill it through
`PopulateBrowserSynchronized` rather than calling `PopulateBrowser` directly,
otherwise its browser is assembled from separately locked reads and can observe
a node halfway through a change.
Analyzer `UA0027` flags `NodeBrowser.DataLock`. See
[migrate/2.0.x/node-states.md](migrate/2.0.x/node-states.md).
`INodeBrowser` also gains `NextAsync(CancellationToken)`, which the async server
browse and translate-path loops use to iterate a browser. The default completes
synchronously with `Next()`, so existing browsers are unaffected; a browser whose
references come from I/O overrides `NextAsync` and awaits there instead of
blocking inside `Next()`. Details in
[migrate/2.0.x/node-states.md](migrate/2.0.x/node-states.md#nodebrowser-gains-an-async-iteration-seam).
## Migrating code that used ApplicationConfiguration.PropertiesLock
`ApplicationConfiguration.PropertiesLock` was removed. It returned the
properties dictionary itself, so `lock (configuration.PropertiesLock)` was
`lock (configuration.Properties)`: the lock was the data it guarded, shared
between the configuration and every caller, taken in an order none of them could
see.
`Properties` is now a concurrent dictionary, so each individual operation is
already atomic and most callers simply drop the `lock`:
```csharp
// was
lock (configuration.PropertiesLock)
{
configuration.Properties["MyKey"] = value;
}
// now
configuration.Properties["MyKey"] = value;
```
The one combination that needs more than a single operation is get-or-add, which
has its own member:
```csharp
// was
lock (configuration.PropertiesLock)
{
if (configuration.Properties.TryGetValue("MyKey", out object? existing))
{
return (MyType)existing;
}
var created = Build();
configuration.Properties["MyKey"] = created;
return created;
}
// now
return configuration.GetOrAddProperty("MyKey", Build);
```
`GetOrAddProperty` deliberately does **not** invoke the factory under a lock, so
a caller cannot hold a critical section across a callback. Under contention the
factory may run more than once; only one result is published and every caller
receives that same instance, so keep the factory free of side effects that would
matter if it ran twice.
One behaviour change is worth knowing: enumerating `Properties` while another
thread writes no longer throws `InvalidOperationException`. It yields a
moment-in-time view instead. Code that relied on the exception to detect
concurrent modification has to detect it some other way.
Analyzer `UA0028` flags the removed member.
## Migrating node types that override FindChild or CreateChild
`NodeState.FindChild` and `NodeState.CreateChild` take
`assignInstanceNodeIds` as their last parameter, and the four argument
`FindChild` / two argument `CreateChild` virtuals are gone. The parameter
defaults to `true`, so **call sites are unaffected**; an override fails to
compile (`CS0115`) until the parameter is added and passed on.
Behaviour note: a node copy — `NodeState.Create(context, source)` and the
`Initialize(ISystemContext, NodeState)` path behind it — now passes
`assignInstanceNodeIds: false`. It no longer asks
`ISystemContext.NodeIdFactory` for identifiers that the copy overwrites
from the source on the very next statement. If your `INodeIdFactory`
counts, reserves or audits every allocation, expect **fewer** calls than in
1.5.378 for the same address space; the resulting NodeIds are unchanged.
Any `NodeState` subclass you own must thread the argument into its
`CreateOrReplace<Child>` calls to get that benefit.
See
[Node states § FindChild and CreateChild](migrate/2.0.x/node-states.md#nodestate-findchild-and-createchild-state-nodeid-assignment)
for the before/after and
[Custom node types and assignment control](NodeManagers.md#custom-node-types-and-assignment-control)
for the runtime rules.
## Adopting replica-consistent NodeIds
When moving a custom 1.5.378 redundant deployment to the 2.0 shared address-space
modules, configure [`UseReplicaNodeIdentity`](ReplicaNodeIdentity.md) with the same
ordered model/instance namespace list on every replica. Namespace 1 remains local
to each ApplicationUri; shared namespaces start at index 2. Do not assume that
previously clock-seeded counters or namespace registration order form a portable
identity contract. Preserve existing agreed IDs explicitly where compatible, or
plan an offline namespace/identifier migration and client cutover.
Unbound legacy shared state is not automatically adopted or renumbered. The
identity module refuses unknown or conflicting stored contracts; see its
new-store provisioning and migration limits before attaching an existing store.
## Removed members on ISession
`ISession.SessionDiagnostics` is removed. It handed out the whole mutable
`SessionDiagnosticsDataType` — the structure the session's diagnostics lock
protects — so a caller could read a field while the owner was writing it.
Every server-side reader wanted one value out of it, and those two values are
now on the interface directly:
```csharp
// was
string? uri = session.SessionDiagnostics?.ClientDescription?.ApplicationUri;
string name = session.SessionDiagnostics?.SessionName ?? string.Empty;
// now
string? uri = session.ClientApplicationUri;
string name = session.SessionName;
```
For anything else in the structure, project it inside `ReadDiagnostics`, which
holds the lock for the duration of the projection:
```csharp
uint reads = session.ReadDiagnostics(diagnostics => diagnostics.ReadCount.TotalCount);
```
`SessionName` is read from the field it was always a copy of rather than from
the diagnostics, because it is assigned once during construction and a value
that cannot change should not cost a lock.
The concrete `Session` still exposes `SessionDiagnostics`; only the interface
loses it.
`ISession.ValidateBeforeActivate` — the synchronous overload with
`out IUserIdentityTokenHandler?` and `out UserTokenPolicy?` parameters — is
removed. It had no caller anywhere in the stack, its samples or its tests other
than tests written for it, and it had been `[Obsolete]` since 1.5.378.
Use `ValidateBeforeActivateAsync`, which returns the same two values as a tuple:
```csharp
(IUserIdentityTokenHandler identityToken, UserTokenPolicy? userTokenPolicy) =
await session.ValidateBeforeActivateAsync(
context, clientSignature, userIdentityToken, userTokenSignature, ct)
.ConfigureAwait(false);
```
The synchronous overload could not verify a user token that required
decryption, so on a secure endpoint it failed closed and directed callers to
the asynchronous path anyway.
The history continuation points moved off `ISession` onto
`ISession.ContinuationPoints`, and no longer pass `object`. `SaveHistory` and
`RestoreHistory` use `IHistoryContinuationPoint`, which carries the point's own
`Guid Id` and extends `IDisposable`:
```csharp
// was
session.SaveHistoryContinuationPoint(state.Id, state);
object? restored = session.RestoreHistoryContinuationPoint(bytes);
// now
session.ContinuationPoints.SaveHistory(state); // the point carries its Id
IHistoryContinuationPoint? restored = session.ContinuationPoints.RestoreHistory(bytes);
```
Implement `IHistoryContinuationPoint` on whatever type you store. The session
previously disposed only those points that happened to implement `IDisposable`
and silently leaked the rest; every point is now disposed.
## Awaiting custom node-manager cleanup
When directly owning a `CustomNodeManager2`, use `await using` or await
`DisposeAsync()` if subsequent work depends on its resources being released.
Unlike the synchronous cleanup in 1.5.x, `Dispose()` now closes admission and
can return while previously admitted operations finish. The monitored-item
manager and address-space nodes remain alive until those operations return.
New service and lifecycle calls after admission closes throw
`ObjectDisposedException`.
An admitted callback may call `Dispose()` to initiate shutdown, but must not
await its own drain with `DisposeAsync()`. Await completion outside the
callback. Server and master-node-manager asynchronous teardown already await
adapted synchronous managers, so server-owned managers need no additional
disposal call.
## Migrating code that called IServerInternal.Set* mutators
`IServerInternal` no longer exposes the twelve `Set*` binding methods or
`CreateServerObjectAsync`. They were startup plumbing: `StandardServer` calls
each exactly once, in one block, to carry a `Create*` factory result into the
datastore. Publishing them on the interface let any holder rewire a running
server, which would leave every component that had already resolved a subsystem
holding the previous instance.
The supported seam is the factory seam, which already existed for every
subsystem here:
| Instead of | Override | Or register in DI |
| --- | --- | --- |
| `SetRoleManager` | `StandardServer.CreateRoleManager` | `IRoleManager` |
| `SetUserManagement` | `StandardServer.CreateUserManagement` (new) | `IUserManagement` |
| `SetMonitoredItemQueueFactory` | `StandardServer.CreateMonitoredItemQueueFactory` | `IMonitoredItemQueueFactory` |
| `SetSubscriptionStore` | `StandardServer.CreateSubscriptionStore` | `ISubscriptionStore` |
| `SetMainNodeManagerFactory` | `StandardServer.CreateMainNodeManagerFactory` | — |
| `SetNodeManager` | `StandardServer.CreateMasterNodeManager` | — |
| `SetSessionManager` | `StandardServer.CreateSessionManager` / `CreateSubscriptionManager` | `ISessionManager`, `ISubscriptionManager` |
| `SetAggregateManager` | `StandardServer.CreateAggregateManagerAsync` | — |
| `SetModellingRulesManager` | `StandardServer.CreateModellingRulesManagerAsync` | — |
| `SetConformanceUnitsManager` | `StandardServer.CreateConformanceUnitsManagerAsync` | — |
`CreateUserManagement` is new in this release, because user management was the
one subsystem with no factory seam. Registering an `IUserManagement` in the
container also switches on the username/password authenticator; override
`CreateUserManagement` if you want the Part 18 §5 model without that.
`SetIdentityRegistry` is **removed with no replacement**. Nothing ever called
it: the supported route has always been
`ServerIdentityRegistryExtensions.RegisterDefaultAuthenticators`, which adds
authenticators to the default registry rather than replacing it.
The methods remain on the concrete `ServerInternalData`, so code that already
held that type keeps compiling. Binding is now refused once the server has
finished starting — a late `Set*` throws `ServiceResultException` with
`BadInvalidState` naming the operation.
## Migrating IServerStartupTask implementations to IServerContext
`IServerStartupTask.OnServerStartedAsync` now receives an `IServerContext`
instead of an `IServerInternal`. `IServerInternal` derives from
`IServerContext`, so the host still passes the same object; only the
declared parameter type changes and an implementation fails to compile
(`CS0535`) until its signature is updated.
`IServerContext` is the ambient view of a running server. It carries what
is genuinely server-wide and nothing else — it deliberately does not hand
out the server's subsystems. A startup task that needs a subsystem takes it
as a constructor dependency, which every implementation in this repository
already did for its other dependencies.
Rewrite the member reads that no longer resolve:
| Was | Now |
| --- | --- |
| `server.Telemetry` | `server.DefaultSystemContext.Telemetry` |
| `server.NamespaceUris` | `server.DefaultSystemContext.NamespaceUris` |
| `server.ServerUris` | `server.DefaultSystemContext.ServerUris` |
| `server.TypeTree` | `server.DefaultSystemContext.TypeTable` |
| `server.Factory` | `server.DefaultSystemContext.EncodeableFactory` |
| `server.DiagnosticsNodeManager.FindPredefinedNode<T>(id)` | `server.FindPredefinedNode<T>(id)` |
| `server.NodeManager.NodeManagers` + a type test | `server.FindNodeManagers<TCapability>()` |
| `server.SessionManager`, `server.SubscriptionManager`, `server.RequestManager`, `server.AggregateManager`, `server.RoleManager`, `server.IdentityRegistry`, … | constructor injection |
`server.MessageContext` is unchanged and remains on `IServerContext`. Do
**not** substitute `server.DefaultSystemContext.AsMessageContext()` for it:
that conversion produces a context with *default* decoding limits rather
than the server's configured `MaxStringLength`, `MaxArrayLength` and
`MaxByteStringLength`, which silently widens what your component accepts.
Tests that hand a `Mock<IServerInternal>` to a startup task keep compiling,
because the mock still satisfies `IServerContext`. Stub the members the task
actually reads now — typically `DefaultSystemContext` and any
`FindNodeManagers<T>()` — or the mock returns `null` and the task fails at
run time rather than at build time.
## Removed members on IServerInternal
The following members had no consumer anywhere in the stack, its samples or
its tests, and have been removed. Each has a direct replacement:
| Removed | Use instead |
| --- | --- |
| `CloseSession(OperationContext, NodeId, bool)` | `CloseSessionAsync(…)` |
| `Status` | `CurrentState` to read, `UpdateServerStatus` to write |
| `ServerDiagnostics` | `UpdateServerDiagnostics(Action<…>)` |
| `DiagnosticsEnabled` | `IDiagnosticsNodeManager.DiagnosticsEnabled` |
| `ModellingRulesManager`, `ConformanceUnitsManager` | the concrete `ServerInternalData`, which owns them |
`MessageContext`, `DefaultSystemContext`, `CurrentState`, `ServerObject`,
`ReportEventAsync`, `CloseSessionAsync`, `DeleteSubscriptionAsync` and
`UpdateServerDiagnostics` all moved *down* to `IServerContext`, the ambient
view of a running server that `IServerInternal` now derives from. They remain
reachable through `IServerInternal` unchanged, so no call site has to move.
`CurrentState` is read-only on the ambient interface; the server itself still
sets it.
## Migrating servers that relied on unserved history advertisement
Server startup now reconciles variables that advertise history with the
historian providers actually wired into the server. If a variable has
`Historizing=true` or `HistoryRead` / `HistoryWrite` access-level bits
from a NodeSet but no `IHistorianProvider` resolves for it, the server
clears the advertisement and masks the attribute read callbacks before
accepting clients. Variables with a provider keep their NodeSet-declared
history surface.
If a client or CTT setup expected `HistoryRead` solely because the
NodeSet declared it, wire a historian instead of relying on the static
flag: use `builder.UseHistorian()` and `.Historize(...)`, register a
provider through the server-wide historian registry, or override
`GetHistorianProvider(NodeState)` in the node manager. See
[Server address-space metadata](NodeManagers.md#server-address-space-metadata) and
[Historical Access](HistoricalAccess.md).
## Migrating custom ISessionManager implementations to ShutdownAsync
`ISessionManager.Shutdown()` is **gone**, replaced by
`ShutdownAsync(CancellationToken)`. `SessionManager` previously started its
session monitor loop with a discarded `Task.Factory.StartNew(...)`, so
`Shutdown()` only *signalled* the loop and returned: the server could
finish tearing down while the monitor was still closing expired sessions
and raising keep-alive events against half-disposed state. There is no
correct synchronous way to wait for that loop — blocking on it would be
sync-over-async — so the synchronous overload was removed rather than
kept as a trap. `ShutdownAsync` cancels the loop and awaits it before
disposing the sessions, matching `ISubscriptionManager.ShutdownAsync`.
**Callers** await instead of calling:
```csharp
// before
server.SessionManager.Shutdown();
// after
await server.SessionManager.ShutdownAsync(cancellationToken)
.ConfigureAwait(false);
```
**Implementers** of `ISessionManager` (for example a manager registered
through `services.AddSessionManager<T>()`) replace `Shutdown` with
`ShutdownAsync`. If your implementation has no background work, return a
completed task:
```csharp
public ValueTask ShutdownAsync(CancellationToken cancellationToken = default)
{
CloseAllSessions();
return default;
}
```
Deriving from `SessionManager` requires no change beyond renaming any
`Shutdown` override: `ShutdownAsync` is `virtual` and the base
implementation already awaits the monitor loop.
## Configuring distributed address-space storage
Direct `InMemoryNodeStateStore` writers require their backend to implement
`ISharedKeyValueStoreConsistency` and provide linearizable operations for
`election/addressspace-sequence`. A bare CRDT store is not a valid writer
backend. Compose it with the shared Raft coordinator using
`HybridSharedKeyValueStore`, or use the fluent consistency registration before
`UseDistributedAddressSpace`.
Use strong state storage for authoritative bootstrap and compacted snapshots.
CRDT payload storage retains merge-only hydration and delta replay without
absence-based cleanup or snapshot compaction. These are configuration
requirements of the distributed-state extension, not a 1.5 persisted-format
migration guarantee. See
[address-space consistency](HighAvailability.md#activepassive-address-space-consistency).
## Migrating SamplingGroupManager create/modify overrides
The public virtual `SamplingGroupManager.CreateMonitoredItem` and
`ModifyMonitoredItem` entry points, and the protected virtual creation
factory, have been removed. They did not accept a separate server-revised
filter, so preserving their dispatch required request-local state merely to
carry that filter through existing overrides.
Use the node manager's `IMonitoredItemManager` pipeline for creation and
modification. For custom item construction, return
`MonitoredItemCreateDecision.Use(factory)` from `OnCreateMonitoredItem` or
`AsyncCustomNodeManager.OnCreatingMonitoredItemAsync`; the stack registers
and owns the returned item. See
[monitored-item creation and lifecycle](NodeManagers.md#monitored-item-creation-and-lifecycle).
Sampling-group creation/modification now receives the original request and
revised filter directly through internal, nonvirtual methods. The request is
not rewritten, and the unrelated monitoring/lifecycle hooks are unchanged.
This is an intentional API removal, not an obsolete forwarding shim.
## Migrating callers of the synchronous MonitoredNode2 notification wrappers
`MonitoredNode2.OnReportEvent` and `MonitoredNode2.OnMonitoredNodeChanged`
are `[Obsolete]`; use `OnReportEventAsync` and
`OnMonitoredNodeChangedAsync`. Nothing in the stack wires the synchronous
pair any more — notifiers are attached through
`NodeState.OnReportEventAsync` and `NodeState.OnStateChangedAsync` — and
both wrappers block the calling thread whenever the bounded notification
channel is full, or whenever the node has an asynchronous read handler.
Blocking there occupies a thread while waiting for a consumer that needs
a thread of its own, which starves the thread pool under load.
```csharp
// before
monitoredNode.OnReportEvent(context, node, e);
// after
await monitoredNode.OnReportEventAsync(context, node, e, cancellationToken)
.ConfigureAwait(false);
```
The wrappers still work and are unchanged in behaviour, so this is a
warning to act on rather than a break.
<a id="ua0029"></a>
## Migrating callers of the SecurityPolicies lookup and cryptography statics
The static lookup and cryptography methods on `SecurityPolicies` have
**moved** to `ISecurityPolicyRegistry`. They read the set of registered
security policies, so they are members of the registry that owns that set
rather than free functions on a constants class.
Moved: `GetUri`, `GetDisplayName`, `GetDisplayNames`,
`IsValidSecurityPolicyUri`, `GetDefaultUris`, `GetDefaultEccUris`,
`GetDefaultDeprecatedUris`, `Encrypt` and `Decrypt`.
**The policy URI constants are unaffected.** `SecurityPolicies.None`,
`SecurityPolicies.Basic256Sha256` and the rest stay exactly where they are,
which is the overwhelming majority of references to this type.
Resolve an `ISecurityPolicyRegistry` where a container is in scope, so the
policies that application registered are the ones used:
```csharp
// before
string uri = SecurityPolicies.GetUri("Basic256Sha256");
// after - the application's own policy set
public sealed class MyService(ISecurityPolicyRegistry policies)
{
public string? Uri => policies.GetUri("Basic256Sha256");
}
```
Where there is no container — configuration loading, for instance — use
the fallback, which carries the built-in policies:
```csharp
string? uri = SecurityPolicies.Default.GetUri("Basic256Sha256");
```
`Encrypt` and `Decrypt` additionally **lose their `ILogger` argument**. The
registry is created with an `ITelemetryContext` and reports through the
logger it made from it:
```csharp
// before
EncryptedData data = SecurityPolicies.Encrypt(certificate, uri, plainText, logger);
// after
EncryptedData data = policies.Encrypt(certificate, uri, plainText);
```
Registering a policy through the container no longer changes what other
code in the same process sees. `AddSecurityPolicy` applies the policy to
the registry that container owns, so two applications hosted together keep
separate policy sets. Use `AddSecurityPolicyRegistry()` to resolve a
registry without contributing a policy of your own.
The `OPCFoundation.NetStandard.Opc.Ua.MigrationAnalyzer` package restores
the removed members as `[Obsolete]` extension members that forward to
`SecurityPolicies.Default`, so a 1.05.378 application compiles with
a warning rather than an error. The `ILogger` argument on the `Encrypt` and
`Decrypt` shims is accepted and **ignored**.
<a id="ua0030"></a>
## Migrating code that drove the server subscription publish pipeline
Twelve members left the server `Opc.Ua.Server.ISubscription`, and the
`SessionPublishQueue` class became internal. The publish pipeline — timer
expiry, message acknowledgement, notification consumption, session release —
is now driven exclusively by `SubscriptionManager` and the publish queue
through an internal contract that only `Subscription` implements. Any holder
of an `ISubscription` (for example via
`IServerInternal.SubscriptionManager.GetSubscriptions()`) could previously
call these members and corrupt the publishing state machine: consume
notifications a client never saw, advance sequence numbers, or release a
subscription its session still owned.
**Deleted outright — remove the call.** `ItemReadyToPublish` and
`ItemNotificationsAvailable` had commented-out bodies since 1.5.x, so every
call was already a no-op. The obsolete parameterless `SessionClosed()` is
gone with them, and so is `TransferSessionAsync`: the server transfers
subscriptions through its internal claim/prepare/commit protocol, reached
via the `TransferSubscriptions` service
(`ISubscriptionManager.TransferSubscriptionsAsync`) — the one-shot direct
transfer bypassed the reservation that protects a transfer against a
concurrently closing source session.
**Internalized — use the service operations.** `PublishTimerExpired`,
`Acknowledge`, `PublishTimeout`, `SubscriptionTransferred`,
`AvailableSequenceNumbersForRetransmission`, `QueueOverflowHandler`,
`SessionClosed(ISession)` and `Publish` are no longer on the interface.
Code that called them was reimplementing a slice of the server; the
supported path is the service set (`Publish`, `Republish`,
`TransferSubscriptions`) and the `ISubscriptionManager` surface
(`SessionClosingAsync` for session teardown). `ResendData`,
`GetMonitoredItems` and the monitored-item service operations remain on
`ISubscription` — resolve the subscription with
`ISubscriptionManager.TryGetSubscription` first, the way the
`Server_ResendData` method handler does.
```csharp
// was: drive the pipeline directly
if (server.SubscriptionManager.TryGetSubscription(subscriptionId, out ISubscription? subscription))
{
subscription.PublishTimerExpired();
subscription.Acknowledge(context, sequenceNumber);
}
// now: the pipeline is server-internal; acknowledgements travel with the
// Publish service request, and the publish timer belongs to the server
Task<PublishResponse> response = server.SubscriptionManager.PublishAsync(
context, subscriptionAcknowledgements, parkSink, cancellationToken);
```
**Custom subscription implementations must derive from `Subscription`.**
`SubscriptionManager.CreateSubscription` and `RestoreSubscriptionAsync`
still return `ISubscription`, but an override returning a type that does not
derive from `Subscription` now fails at creation with `Bad_InternalError`
instead of publishing partially (transfer already required the concrete
type). Derive from `Subscription` and override the behaviour you need; the
pipeline members are explicit implementations of the internal contract and
are not virtual.
The no-`[Obsolete]`-shim rule [above](#why-there-is-no-obsolete-shim)
applies here for the same reason: `ISubscription` is implemented by
downstream code, and re-adding an interface member later would break every
implementer. Analyzer `UA0030` flags each removed member on the migration
path and names the replacement.
## Migrating channel subclasses that guarded state with DataLock
`UaSCBinaryChannel.DataLock` has been **removed**. The channel no longer
serialises any of its own state on it, so taking it excluded nothing.
A monitor cannot be held across an `await`, and the secure channel open
path has to be able to await once a private key may be served over a
network — see [Crypto provider](CryptoProvider.md). The channel now uses
an internal gate that can be entered from a synchronous or an
asynchronous path. Unlike a monitor the gate is **not re-entrant**: every
channel path that used to take the lock while already holding it now
calls a lock-free `Core` variant instead.
That has one consequence for subclasses. The channel calls
`HandleSocketError`, `NotifyMonitors` and `CompleteReverseHello` from
paths that may already hold the gate, so an override of any of them must
not call back into a channel method that takes it — `ForceChannelFault`
and `SendResponse` in particular. Such an override would have silently
nested before and will now block.
For the same reason `SaveIntermediateChunk`, `GetSavedChunks` and
`DoMessageLimitsExceeded` take an additional `gateHeld` argument. It says
whether the calling frame already holds the gate, so that an override
which tears the channel down can pick the locking or the lock-free path:
```csharp
// before
protected override void DoMessageLimitsExceeded()
{
base.DoMessageLimitsExceeded();
Shutdown(new ServiceResult(StatusCodes.BadResponseTooLarge));
}
// after
protected override void DoMessageLimitsExceeded(bool gateHeld)
{
base.DoMessageLimitsExceeded(gateHeld);
if (gateHeld)
{
ShutdownCore(new ServiceResult(StatusCodes.BadResponseTooLarge));
return;
}
Shutdown(new ServiceResult(StatusCodes.BadResponseTooLarge));
}
```
There is no drop-in replacement to offer across an assembly boundary,
because the gate has to be entered asynchronously on the open path and
its correctness depends on rules that only hold inside the channel
implementation. A subclass outside this stack that guarded **its own**
state with `DataLock` should introduce its own synchronisation:
```csharp
// before
lock (DataLock)
{
m_myState = value;
}
// after
private readonly System.Threading.Lock m_myLock = new();
using (m_myLock.EnterScope())
{
m_myState = value;
}
```
A subclass that took `DataLock` in order to be mutually exclusive with
the **channel's** state transitions was already relying on an
implementation detail, and can no longer do so.
## Transport resource limits
Applications migrating from 1.5.x have a server-wide budget for retained
intermediate-message buffers. With the reference server's 4 MiB maximum message
size, the default budget is **64 MiB**, and channels without an activated session
may fill only the lower **32 MiB**. A chunk that does not fit discards its partial
message and closes the channel with `BadTcpNotEnoughResources`. Final chunks,
single-chunk requests, response buffers, and client buffers are not charged to
this reassembly budget.
For workloads with many simultaneous large requests, set
`WithChunkReassemblyBudget(maxBytes)` on the Dependency Injection (DI) server builder or assign
`ServerBase.ChunkReassemblyBudget` before startup. A host opening listeners
directly can share a budget through `TransportListenerSettings.ChunkReassemblyBudget`.
See [incomplete messages](RateLimiting.md#incomplete-messages) for sizing and
sessionless configuration. General buffer-manager limits remain opt-in.
Server-channel `ChannelLifetime` also bounds an unfinished message from its
first retained chunk, even if more chunks keep arriving. Size this lifetime
for legitimate large transfers without relying on continuation chunks to
extend it indefinitely. A zero or negative value uses the 30-second default
for message assembly; it does not disable assembly cleanup. See
[incomplete-message limits](Transports.md#incomplete-message-resource-limits).
Kestrel TCP and UACP WebSocket listeners honor configured connection-admission
and channel limits, including pending admissions. Size `MaxChannelCount` for
the intended deployment rather than relying on these bindings to ignore it.
Managed channel membership is based on committed live sessions rather than
activation-response counts. Custom session managers can implement the optional
`ISessionBindingProvider` capability; custom hosts can inject a provider without
changing existing callback contracts. A lookup snapshot does not replace normal
request authentication and authorization.
## Migrating channel subclasses that override HandleIncomingMessage
`UaSCBinaryChannel.HandleIncomingMessage` and `OnChunkReceived` have been
**removed**, as has the `protected WriteAsymmetricMessage` overload that
returned the signature through an `out` parameter. The receive loop calls
`HandleIncomingMessageAsync` and `OnChunkReceivedAsync`, so that the
secure channel open path can await a private key served over a network —
see [Crypto provider](CryptoProvider.md).
A synchronous override cannot be kept working underneath the
asynchronous path without defeating the point of it, so **an existing
override must be moved**. The signature gains a `CancellationToken` and
returns `ValueTask<bool>`:
```csharp
// before
protected override bool HandleIncomingMessage(
uint messageType, ArraySegment<byte> messageChunk)
{
...
}
// after
protected override async ValueTask<bool> HandleIncomingMessageAsync(
uint messageType, ArraySegment<byte> messageChunk, CancellationToken ct)
{
...
}
```
An override that has nothing to await can return a completed value
without going asynchronous at all:
```csharp
protected override ValueTask<bool> HandleIncomingMessageAsync(
uint messageType, ArraySegment<byte> messageChunk, CancellationToken ct)
{
return new ValueTask<bool>(HandleSynchronously(messageType, messageChunk));
}
```
The buffer-ownership contract is unchanged: return `true` when the
implementor takes ownership of the chunk, and it will not be returned to
the buffer manager for you.
`ReadAsymmetricMessageAsync` and `WriteAsymmetricMessageAsync` return
`AsymmetricMessage` and `AsymmetricWriteResult` rather than using `out`
parameters, which an asynchronous method cannot have. Use
`WriteAsymmetricMessageAsync` in place of the removed synchronous
overload.
## Migrating custom IUserDatabase implementations
`IUserDatabase` gained four members. A store now persists user metadata
alongside credentials, so disabled and `MustChangePassword` decisions survive a
restart and an administrative password reset is a single transaction rather than
a delete followed by a create:
```csharp
IReadOnlyList<UserManagementDataType> GetUsers();
bool CreateUser(
string userName,
ReadOnlySpan<byte> password,
ArrayOf<Role> roles,
UserConfigurationMask userConfiguration,
string description);
bool ResetPassword(
string userName,
ReadOnlySpan<byte> newPassword,
UserConfigurationMask userConfiguration,
string description);
bool UpdateUserMetadata(
string userName,
UserConfigurationMask userConfiguration,
string description);
```
The five 1.5.378 members are unchanged. Implement the new ones on your store, or
derive from `LinqUserDatabase` / `JsonUserDatabase`, which provide in-memory and
atomic file-backed transactions respectively.
Each mutation must commit as one transaction, and a rejected or failed write must
leave both the live and the persisted record unchanged. `ChangePassword` must
clear `UserConfigurationMask.MustChangePassword` in the same transaction as the
password it commits. `ResetPassword` must preserve the user's identity and roles
and must not delete and recreate the user.
There is no optional-capability fallback: `UserManagement` requires these members
and no longer keeps metadata only in memory, so a store that cannot persist
metadata should reject the write by returning `false` rather than silently
accepting it.
## Migrating from 1.05.377 to 1.05.378
### Asynchronous as default
The server now supports `AsyncNodeManagers`; see
[Server Async (TAP) Support](AsyncServerSupport.md). The client APIs are
async by default and all synchronous and APM-based API has been
deprecated. To migrate, update your code to use the `Async` version of
every API where possible. Not recommended but for expedience you can
call the `Async` version synchronously with
`GetAwaiter().GetResult()`.
### Observability
Observability is now plumbed through `ITelemetryContext`. The legacy
static `Utils.SetLogger` / `Utils.Trace*` model has been removed in
2.0. See
[`migrate/2.0.x/telemetry.md`](migrate/2.0.x/telemetry.md) for OLD
vs NEW snippets, the per-type constructor matrix, and the full
inventory of removed / `[Obsolete]` `Utils` APIs.
Configuration-level trace apply APIs were removed as well: `TraceConfiguration.ApplySettings()` and `ApplicationConfigurationBuilder` trace setters (`SetOutputFilePath`, `SetDeleteOnLoad`, `SetTraceMasks`). Configure logging through `ITelemetryContext` instead.
## Migrating from 1.04 to 1.05
A few features are still missing to fully comply with 1.05, but
certification for v1.04 is still possible with the 1.05 release.
## Support
For additional migration support:
- Review sample applications in the repository.
- Check unit tests for usage patterns.
- Use the
[`OPCFoundation.NetStandard.Opc.Ua.MigrationAnalyzer`](https://www.nuget.org/packages/OPCFoundation.NetStandard.Opc.Ua.MigrationAnalyzer)
package — 26 implemented analyzer rules through `UA0030` (excluding
`UA0013`, `UA0016`, `UA0017`, and the shim-only `UA0029`) map across the
[`migrate/2.0.x/`](migrate/2.0.x/README.md) guides and the cross-cutting
notes on this page; 14 rules apply safe edits via a code-fixer. `UA0029`
is currently a runtime-shim/manual marker surfaced through `CS0618`, not an
analyzer diagnostic.
- Open an issue on
[OPCFoundation/UA-.NETStandard](https://github.com/OPCFoundation/UA-.NETStandard/issues).