Files
UA-.NETStandard/docs/MigrationGuide.md
T
Marc Schier 7411654c8d Complete OPC UA Part 11 Historical Access (#4390)
# Description

Completes the OPC UA Part 11 Historical Access work requested by #4387
and
the historian framework integration requested by #4400.

The conformance/evidence catalog covers all 37 released UACore 1.05
Historical Access profiles: 15 Server facets and 22 Client facets,
together
with the standard aggregate functions and their conformance units.
Server
facets are advertised only when the resolved providers expose their
required
interfaces and capabilities.

## Server and provider support

- Completes raw, modified, at-time, processed, annotation, structured,
and event history.
- Dispatches best-effort, bulk, and transactional updates with aligned
statuses, old values, diagnostics, and rollback state.
- Supports mixed history-update detail types and batched
structured/annotation operations.
- Uses composite identities and exclusive cursors for same-timestamp
structured, modified, and event values.
- Captures live data and events, installs historical configuration
objects, and emits typed audit payloads.
- Derives aggregate monitoring filters from per-node historian
capabilities and rejects unsupported processed aggregates before
provider dispatch.
- Supports tri-state `Historizing`: set, clear, or preserve
provider-owned state.

## Client support

- Exposes modified values together with `ModificationInfo`.
- Adds event-history reads and event insert/replace/update/delete
operations.
- Adds structured and annotation batching with strict response
validation.
- Shares continuation handling and release-on-abandon across read
families.
- Accepts inherited standard event fields rooted at event subtypes.

## Review hardening

- Registers DI-selected historians before node-manager reconciliation
and capability publication, while preserving provider ownership.
- Uses committed Raft read barriers for linearizable `TryGetAsync` and
`ScanAsync`.
- Keeps claimed continuation state immutable until a fresh successor is
saved, restoring the original after transient failures.
- Uses exact-incarnation compare-and-delete so delayed cleanup cannot
remove a restored same-ID continuation.
- Cleans up indeterminate initial and replacement saves, and propagates
shutdown cancellation through cleanup resolution.
- Preserves legacy continuation envelopes/cursors and distinct
annotation parent/property identities.
- Deletes every structured entry at a requested timestamp and uses the
complete modified-history ordering tuple.
- Shares native/fallback at-time and AnnotationCount calculations,
including reverse endpoints and cross-framework fractional intervals.
- Primes modified aggregate items before buffered live delivery and
deduplicates history/live overlap using provider-specific identities.
- Keeps committed Modify results successful while reporting priming
failures
  through the monitored item's notification queue.
- Keeps protected-notification state live-only for queues larger than
one.
Queue size one retains the newest notification without pinning errors or
transferring priority during resizing. Durable restore retains ordinary
definitions, last values/errors, and raw queues without recreating
priority.
- Isolates aggregate calculation, modification preparation, and
historical/live
handoff in `AggregationFilterHandler`, retaining existing
provider/factory
wiring and supported past-start behavior. The larger-queue protection
policy
  is unchanged pending the open review discussion.
- Uses one `IMonitoringFilter` owner for protocol filters or the
aggregation
handler, eliminating parallel effective-filter storage and retaining the
current definition during preparation. The original client filter stays
distinct.
- Integrates current master, retaining custom monitored-item creation
decisions and per-node history callbacks.

## Redundant-server alignment and samples

- Adds a protected shared historian with immutable segments, manifest
CAS publication, writer fencing, and restart recovery.
- Persists portable continuation state before exposing it to clients and
transfers ownership during mirrored-session takeover.
- Rejects eventual-consistency and active/active multi-writer historian
configurations rather than silently degrading.
- ReferenceServer and ConsoleReferenceClient demonstrate discovery,
paging, raw/modified/at-time/processed reads, annotation/structured
CRUD, event capture, and event CRUD.
- RedundantServer and RedundantClient demonstrate active/passive
history, continuation recovery after replica termination, and
post-promotion writes.
- Updates Historical Access, High Availability, profile, migration, and
sample documentation.

## Compatibility

- New 2.0 collection boundaries use `ArrayOf<T>` and public byte
payloads use `ByteString`.
- Removes the legacy public virtual
`SamplingGroupManager.CreateMonitoredItem` /
`ModifyMonitoredItem` entry points and protected creation factory, as
agreed
  in review. Migration guidance points to the monitored-item manager and
  construction-decision APIs.
- Retains established persisted formats and current write layouts.
Retired interim
notification-state formats (sample v2 / shared v4) are rejected, as
agreed in review.
- Keeps the historian integration compatible with .NET Framework and
NativeAOT.

## Validation

### Latest CI source repair

`73c619435` forwards the existing cancellation token at both
predefined-node
creation calls in the PR-added History event fixture. The merged
lifecycle
overload exposed these two CA2016 errors, which blocked History jobs,
the
solution build matrix, and CodeQL on GitHub and Azure. The exact
compiler
failure was reproduced locally; the repaired fixture passes 4/4
integration
cases on net10.0 and 4/4 on net48 with clean scoped diagnostics. No
assertions,
tests, coverage thresholds, or CI configuration were weakened.

The repaired History jobs on Linux/macOS and all four Azure solution
builds
now pass. The Windows all-TFM GitHub job instead lost its hosted
runner's
connection; no build log was recoverable, and GitHub recorded a
runner-loss
annotation rather than a compiler/test diagnostic. One unchanged retry
was
requested. Remaining checks are monitored with
`gh pr checks --watch --fail-fast --interval 30`; CI is not yet reported
as green.

### Latest base integration

`bd52e5fea` merges upstream `master` at `da7412c42`. The lifecycle
conflict
retains upstream's shared cancellation-aware registration helper and the
historian behavior. The hosted-historian fixture forwards its existing
token
to the new lifecycle overload. GDS project renames and all three AOT
test
hosts are retained, with their project references resolving after the
merge.

| Integrated scope | net10.0 | net48 |
| --- | --- | --- |
| Server lifecycle, fluent authoring/import, historian, monitored-item
and hosting regressions | 732 passed | 732 passed |
| NodeState lifecycle regressions | 216 passed | 216 passed |
| Automatically merged Raft client fixtures | 28 passed | 28 passed |

No selected tests failed or were skipped. The manually resolved files
pass
scoped formatting/analyzer checks. One CA1861 warning remains in the
incoming
`NodeSetImportIntegrationTests.cs`; that file is byte-identical to
upstream
master and was not rewritten or suppressed during integration.

### Latest feedback follow-up

`102954eaa` replaces split filter references with the shared
`IMonitoringFilter`
contract implemented by protocol filters and `AggregationFilterHandler`.
Targeted server regressions pass **103/103 on net10.0 and 103/103 on
net48**;
scoped formatting/analyzers are clean, and the updated XML-documentation
inventory has zero gaps across 188 non-generated PR C# files.

`93c5b5db8` renames `AggregationFilterHandler`, makes it the owner of
the
server-revised aggregate filter while preserving the original client
filter,
and removes the retired interim notification-state readers. Server
regressions
pass **101/101** and shared-store regressions **64/64**, on both net10.0
and
net48, with no failures or skips. Runtime-file formatting/analyzers are
clean.

`5ccf45630` completes the public/internal XML-documentation sweep. The
Roslyn
inventory finds zero undocumented eligible declarations across all 186
non-generated PR C# files; the 110-file documentation slice changes only
XML
comments and spacing. `f17765475` applies the three requested Markdown
edits.

### Earlier feedback follow-ups

`a53950737` removes single-slot notification pinning and extracts
aggregate
implementation from MonitoredItem. Targeted sampling, aggregate
modification,
history/live handoff, queue/lifecycle, restore, and serialization cases
pass
**101/101 on net10.0 and 101/101 on net48**, without failures or skips.
Scoped formatting/analyzers are clean; the focused review found no
significant
issues. The final formatted monitored-item fixtures also pass 45/45 on
net48.

The preceding `b21555568` removes the legacy sampling API bridge and
durable
notification-priority state. Its targeted Server cases passed 97/97 and
shared
subscription-store cases passed 64/64 on each framework. The broader
evidence
below remains pinned to its original tested commit, not attributed to
these
follow-ups.

### Earlier integrated-implementation validation

Validated implementation commit: **`3efae597f`**. The following commit,
`f6dbefb1c`, only adds two explanatory comment lines for the final
standards
review; it changes no executable code.

| Scope | net10.0 | net48 |
| --- | --- | --- |
| Server | 5,187 passed; 56 skipped | Affected surface: 2,160 passed; 1
reproduced baseline failure; 56 skipped |
| Client | 2,202 passed; 2 skipped | 2,204 passed; 5 skipped |
| History integration | 519 passed; 21 skipped | 519 passed; 21 skipped
|
| Redundancy server | 641 passed | 641 passed |
| Redundancy client | 124 passed | 124 passed |
| Core shared-store regression suite | 23 passed | 23 passed |

All six affected samples passed non-incremental Release/net10.0 builds
with
zero warnings and errors: ConsoleReferenceClient,
ConsoleReferenceServer,
RedundantServer, RedundantClient, MinimalBoilerServer, and
PumpDeviceIntegrationServer.

The published self-contained win-x64 NativeAOT executable is 116,924,928
bytes and has no CLR header or managed runtime dependency. Direct
execution
passed **HistoryAotTests 3/3** and **RaftAotTests 2/2**.

Final standards and specification reviews found no confirmed outstanding
high/medium functional gaps or hard standards violations. The remaining
constructor-purpose clarification is addressed in `f6dbefb1c`.

### Reproduced baseline exceptions

The net48 hosted-startup timeout also reproduces in a pristine worktree
at
the previous PR head, `24cf1416d`, in

`RegisterPostStartRegistriesWiresHistorianAndAliasStoresOnPlainServerAsync`,
with the same subsequent certificate-leak assertion. The corresponding
renamed case fails before startup in the reviewed branch as well. This
is
reported separately from the net48 affected-surface results, not counted
as
a passing full Server suite. The net48 matrix selected the historian,
aggregate, monitored-item, fluent, and continuation surfaces and
excluded
the Hosting namespace.

`DurableDataValueQueueVerifyReferenceBatchingAsync` failed at item 1000
in
the net48 affected-surface run and passed its single isolated rerun. The
same
failure at the same assertion reproduces on pristine `849e16acc`; the
test,
sample queue, queue factory, and batch persistor are unchanged. The
original
failure remains in the table rather than being erased by the rerun.

### CI source repairs

- `4be7eb8f7` keeps diagnostics/configuration managers out of
distributed
address-space replication. Those managers inherit the source interface,
but their live server state and redundancy metadata must remain
replica-local.
  The ownership regression passes on net10.0 and net48, and all nine
  redundancy sample CI tests pass locally.
- `d17f467b3` completes the sample startup repair: core managers are
also
replica-local; the startup banner no longer advertises readiness before
initialization; the producer starts after distributed services; and
native
Raft startup no longer forces disruptive extra elections. The full
sample
suite passed 9/9, with initialized `RedundancySupport=Hot`, and focused
  Raft/address-space regressions passed 8/8 and 3/3.
- `81b0b72be` moves the unchanged distributed-historian NativeAOT
scenario
into a smaller, always-run companion executable to bound Apple's linker
input. All 137 AOT tests remain present; the moved test and helpers are
  unchanged. GitHub and Azure publish/run both native executables, with
separate result directories where they share a job. The companion passed
actual Windows NativeAOT execution. Linux and Intel macOS CI passed both
  executables, but this split alone did not fix ARM64 macOS linking.
The remaining historian graph is rooted by ReferenceServer startup, not
just the relocated test. No test exclusion or speculative linker setting
  was added to conceal it.
- `8a5842913` isolates the independent MCP test graph into an always-run
native host. The existing MCP source and assembly leak hooks are linked
  unchanged, and evaluated compiler inputs prove exactly one owner for
  every test source: 133 main + 3 MCP + 1 historian = 137 declarations.
All three hosts run on every AOT platform. The main Windows native
object
is 9.35% smaller; both changed publishes had zero diagnostics. MCP
passed
  3/3; the identical main executable passed 133/133 on one unfiltered
followup after two initial endpoint-discovery connection failures, which
  remain recorded in the local evidence.
- The previous Intel macOS job successfully published and executed its
native
tests, then failed on artifact-upload DNS (`ENOTFOUND`). No upload gate,
  shared environment setting, or cache configuration was disabled.

The first repair round also encountered the unrelated
`MetricsAreEmittedForChannelLifetimeAsync` timing failure on macOS Core.
Neither that test nor channel-manager code is changed by this PR, and
its
assertions remain intact. It passed unchanged on the final repair head.

On `d17f467b3`, the Linux and macOS redundancy sample jobs pass; the
remaining
failure was ARM64 Apple's `too many large addends` assertion. The
verified
upstream relocation-anchor fix (dotnet/runtime#124721, backport
dotnet/runtime#132171) is not present in the shipping ILCompiler
10.0.11.
An experimental multi-module probe failed and was rejected, not added to
CI.
On `8a5842913`,

[`aot-macos-latest`](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/34102158680/job/101678934057)
successfully publishes and executes all three native hosts on ARM64:
136 main runtime cases, 1 historian case, and 3 MCP cases, with no
skips.
The previous Apple linker blocker is resolved. Linux NativeAOT also
passes.
No assertion, test, shared environment setting, cache, or required gate
was
weakened.

The same CI run reports a separate macOS Sessions teardown failure: all
662 executed tests pass, but the global leak assertion detects one
undisposed certificate. The MCP partition changes no runtime, Sessions,
or
test-fixture code. A single unchanged diagnostic rerun is queued once
GitHub
permits rerunning that job; the failure is not suppressed or counted as
green.
Other CI checks are still pending.

## Related issues

- Fixes #4387
- Fixes #4400

## Checklist

- [ ] I have signed the CLA and read the contributing guide.
- [x] I have added regression tests and directly related documentation.
- [x] I have retained working reference and redundant-server sample
wiring.
- [x] Final validation and review evidence is complete, including the
baseline exceptions above.
- [ ] All required CI checks pass; the fail-fast rerun for `73c619435`
is pending.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9dbd9527-d818-47a0-984c-fbb1472d3d6b
2026-09-08 11:32:23 +02:00

37 KiB

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/ 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 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:

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/ — landing page and symptom-based thematic sub-doc index.
1.05.377 1.05.378 § inline below — small enough to keep on this page.
1.04 1.05 § inline below — 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.

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.

// was
lock (server.DiagnosticsLock)
{
    server.ServerDiagnostics.RejectedSessionCount++;
}

// now
server.UpdateServerDiagnostics(diagnostics => diagnostics.RejectedSessionCount++);

The same shape applies to sessions and subscriptions:

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:

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.

// 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:

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:

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:

// 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:

// 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.

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:

// 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:

// 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 for the before/after and Custom node types and assignment control for the runtime rules.

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:

// 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:

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:

(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:

// 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.

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 and Historical Access.

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:

// 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:

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.

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.

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.

// 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.

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:

// 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:

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:

// 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.

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.

// 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 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. 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:

// 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:

// 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.

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.

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>:

// 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:

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 from 1.05.377 to 1.05.378

Asynchronous as default

The server now supports AsyncNodeManagers; see Server Async (TAP) Support. 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 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 package — 26 implemented analyzer rules through UA0030 (excluding UA0013, UA0016, UA0017, and the shim-only UA0029) map across the migrate/2.0.x/ 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.