romanett 5b03e9afa4 Channel send path: seal responses in the writer, lock-free gate, fewer locks and allocations per request (#4782)
Carved out of #4771 (roadmap item A1 of the o6 benchmark gap analysis):
everything except running requests to completion on the receive loop.
#4771 keeps run to completion, stacked on this PR, for a later release.

Requests still go through the fair request queue and its workers, as on
master. What changes is the channel around them:

- the response is encoded without the channel gate;
- the channel's single writer numbers, secures and sends;
- requests take fewer locks and allocations on the channel.

No wire, configuration or public API change.

## Results

Paired A/B against master `6cfb8cf19` (with #4767). The builds alternate
per round on the same machine, and the table shows medians of 5 rounds
with the throughput range of the rounds in brackets. The machine was
shared with other work, so the CPU and throughput ranges are wide;
allocated bytes per request are deterministic.

- **o6read** uses the native open62541 client workers of the
o6-automation benchmark, in the o6 2.0.1 configuration:
`AsyncCustomNodeManager`, Server GC, queue = clients × outstanding + 3.
- **"4 cores"** pins the server to 4 cores.
- **The other rows** use the harness's .NET client: 20 sessions unless
noted, workstation GC, ReferenceServer.
- **Contention** counts runtime lock-contention events in the measured
window.

| Scenario | req/s | Server CPU µs/req | Alloc B/req | Contention |
|---|---|---|---|---|
| o6read 10×100, 24 cores | 254,600 → 264,700 (+4 %) [228–292k →
255–270k] | 67.4 → 69.5 | 5,874 → 4,709 (**−20 %**) | 6,766 → 1,811 |
| o6read 10×1000, 24 cores | 248,900 → 241,300 (−3 %) [231–258k →
233–260k] | 69.0 → 71.3 | 5,866 → 4,718 (**−20 %**) | 6,080 → 1,456 |
| o6read 10×100 encrypted, 24 cores | 203,900 → 232,000 (**+14 %**)
[111–226k → 204–264k] | 71.6 → 70.2 | 5,985 → 4,752 (**−21 %**) | 5,166
→ 1,288 |
| o6read 10×100 `--o6-async 0` (`CustomNodeManager2`), 24 cores |
235,600 → 243,900 (+4 %) | 40.1 → 38.8 | 6,702 → 5,886 (−12 %) | 148k →
124k |
| o6read 1 client × 1000 (one channel) | 64,300 → 92,600 (**+44 %**)
[52–69k → 76–100k] | 79.8 → 74.5 (−7 %) | 6,003 → 5,063 (−16 %) | 224 →
128 |
| o6read 10×100, 4 cores | 156,600 → 140,400 (−10 %, noise: rounds
139–192k → 121–184k) | 25.0 → 28.3 | 5,435 → 4,688 (−14 %) | 97 → 184 |
| o6read 10×1000, 4 cores | 107,100 → 125,200 (**+17 %**) [103–116k →
120–136k] | 36.5 → 31.7 (**−13 %**) | 9,966 → 4,767 (**−52 %**) | 312 →
160 |
| o6read 10×100 encrypted, 4 cores | 103,300 → 126,300 (**+22 %**)
[102–105k → 115–143k] | 37.9 → 31.3 (**−17 %**) | 5,498 → 4,736 (−14 %)
| 46 → 29 |
| o6read 10×100 `--o6-async 0`, 4 cores | 186,600 → 187,700 (+1 %) |
21.1 → 21.0 | 6,587 → 5,915 (−10 %) | 17.7k → 4.2k |
| read --nodes 1, 20 sessions | 208,300 → 205,900 (−1 %) | 49.1 → 48.3 |
4,905 → 4,621 (−6 %) | p50/p99 0.072/1.18 → 0.072/1.26 ms |
| read --nodes 1, 200 sessions | 216,400 → 208,600 (−4 %) | 42.0 → 43.2
| 4,790 → 4,518 (−6 %) | p50/p99 0.606/3.56 → 0.615/4.05 ms |
| read --nodes 100 | 31,950 → 32,470 (+2 %) | 278 → 253 (−9 %) | 73,702
→ 73,436 | p50/p99 0.290/2.51 → 0.283/2.48 ms |
| browse | 38,380 → 40,460 (+5 %) | 162 → 161 | 39,305 → 38,981 | p50
0.349 → 0.330 ms |
| sub (5 × 100 items, 100 ms) | 88,190 → 89,010 notif/s | 11.1 → 10.7 |
159 → 153 | p50/p99 20.7/64.3 → 20.8/66.0 ms |

**Where it helps:**
- Allocation per request falls in every scenario, by 20 % for o6read.
- Lock contention falls by 70–80 % for o6read.
- Throughput rises where the channel gate serialised the work:
  - one deep pipeline on one channel: +44 %;
  - encrypted: +14 % on 24 cores, +22 % on 4 cores;
  - 1000 in flight on 4 cores: +17 %.

**Where it does not:** CPU per request at 24 cores is unchanged. The
requests still go through the fair queue's workers, and the hand-off to
a worker and back is what #4771 removes. The 4-core 10×100 row spread as
much within each side as between the sides.

## Changes

### Sending
- **Seal in the writer.** The producer encodes the response without the
channel gate and queues it unsealed. The channel's single writer takes
the queued responses in order under a per-channel send-order lock: it
assigns sequence numbers, selects the current token, signs and encrypts,
and sends the batch. Messages that number themselves (OpenSecureChannel,
asymmetric faults, the client's requests) hold the same lock until they
are queued. Token changes that can dispose a token take it as well.
- **Reconnect.** The old transport is detached before the new token is
activated. Unsealed responses still queued for it are then dropped
without taking sequence numbers. The new transport is attached and the
OpenSecureChannel response numbered under one hold of the send-order
lock, so the response is the first message on the new transport. The
channel opens again only after that.
- **Failure past the sequence numbers.** A message whose security fails
after its chunks took sequence numbers stops all numbering on that
transport. The writer drops the messages producers numbered for it after
the gap, and reports a transport error once it has left the send-order
lock. That faults the channel (server) or reconnects (client).
- **Numbered writes without the lock.** The writer takes writes that
their producers numbered without the send-order lock, because they are
queued in number order. A client channel queues only such writes, so its
writer no longer waits for the lock that its request threads take.
- **Writer on the pool.** The writer always starts on the thread pool.
Running it on the producer's thread sent batches of one message.
- **Buffers.** The encoded message is a struct in the write-queue entry.
A small single-chunk message moves to a right-sized buffer only when
writes are already queued, so deep pipelines no longer exhaust the
bounded buffer pool (−52 % allocation at 10×1000 on 4 cores).

### Locks and allocations per request
- **`ChannelGate`** takes the gate with one compare-and-exchange when it
is free, and queues waiters under a lock only when it is not.
`SemaphoreSlim` took its monitor on every wait and release, which the
receive loop does for every message. The contract is unchanged: not
re-entrant, FIFO handoff, cancellable waits, synchronous completion when
free. The transport's send lock is a `ChannelGate` too.
- **Namespace and server tables.** Every encoder and decoder reads
`ServiceMessageContext.NamespaceUris`, `ServerUris` and
`MappingVersion`. They are now read lock-free from one immutable
snapshot that setters swap atomically.
- **Allocation-free tracking.** Tracking a pending request
(`PendingRequestScope`) and handing a decoded request out of the gate
allocate nothing.
- **Single-chunk decode.** A request in one chunk is decoded from that
chunk's buffer.
- **Fair-queue entry.** An entry coordinates its cancellation
registration with an interlocked state (`RegistrationState`) instead of
a lock object.

### Client fix
`Session.CloseAsync` disposed the session synchronously, and `Dispose`
waits for the async dispose of the session and its subscription engine.
Closing 1000 sessions at once blocked one pool thread per session while
that dispose needed pool threads, and the close took minutes in
`ServerManySessionsLoadTestAsync(1000)`. `CloseAsync` now awaits
`DisposeAsync`, and dispose awaits an engine that implements
`IAsyncDisposable`, as `DefaultSubscriptionEngine` now does.

## Behaviour notes
- **Wire order and tokens.** Sequence numbers stay strictly increasing
in wire order, and the chunks of one message stay contiguous. Token
renewal applies at a message boundary. After a reconnect, the
OpenSecureChannel response is the first message on the new transport.
- **Back-pressure** (#4707) is unchanged. The receive loop stops reading
above 100 queued writes.
- **Client.** `Session.CloseAsync` no longer blocks a thread on the
dispose.

## Not in this PR
The striped server-stop tokens of #4771 are dropped. Since #4767 a
server request no longer registers with the stop token, because the
deadline monitor polls it.

## Testing
- `UaSCBinaryChannelSendOrderTests` covers:
  - wire order and random interleaving;
  - token renewal (decrypt and verify) for five policies;
  - buffers returned once;
- a seal failure after numbering stops the channel, and a message
numbered after the gap is not sent;
  - the replaced transport;
  - back-pressure;
  - a response that cannot be encoded is answered with a fault.
-
`TcpReconnectKeyAgreementTests.AResponseQueuedForTheDroppedTransportIsNotSecuredWithTheNewTokenAsync`
(new) holds the old transport's sends during a reconnect. It fails on
the previous order. The seal-failure test fails without the gap check.
- Also run: `ChannelGateTests`, `TcpByteTransportTests`,
`ServiceMessageContextMappingTests`.
- Local, net10.0:
- Opc.Ua.Core.Tests (Stack.Server, Transport, Tcp, ChannelGate): 2739
passed, 0 failed;
  - Opc.Ua.Configuration.Tests: 241 passed, 0 failed.

net48 builds. `dotnet format whitespace --verify-no-changes` passes on
the changed files.
- CI: the `CI` workflow on this head is running; the commits were tested
together with run to completion in #4771 (its last full CI run passed).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:51:14 +02:00
2020-05-15 19:41:55 +02:00
2021-07-26 10:06:51 +03:00

OPC UA .NET Standard Stack

Release NuGet Downloads CI CodeQL Coverage Nightly Stress Tests Connection Stability Foreign Interop HA Long-Haul CTT Regression

🆕 This is version 2.0 of the OPC UA .NET Standard Stack (current master).

Looking for the supported 1.x release? It lives on the master378 branch (last release: 1.5.378). All new feature work happens here on master; master378 continues to receive security and critical-bug fixes for the 1.x line.

The official OPC Foundation reference implementation of OPC UA for .NET — a certified, cross-platform stack with client, server, PubSub, GDS, complex types, and source-generated tooling. Used in production across industrial control, manufacturing, energy, and IoT systems.

📦 What it is

  • A full-stack OPC UA implementation — Core / Client / Server / PubSub / GDS / LDS / Complex Types / Device Integration / Positioning libraries built on .NET, with UA-TCP and HTTPS transports.
  • Cross-platform — runs on .NET 10, .NET 9, .NET 8 (LTS), .NET Framework 4.8; ships Native-AOT-friendly assemblies.
  • Certified for compliance — the reference server has been certified through an OPC Foundation Certification Test Lab and is continuously verified against the latest Compliance Test Tool (CTT).
  • Companion-spec coverage — Part 9 (Alarms & Conditions), Part 11 (Historical Access), Part 13 (Aggregates), Part 16 (State Machines), Part 17 (Alias Names), Part 18 (Role Management), Part 20 (File Transfer), Part 100 (Device Integration), Part 110 (Asset Management Basics), Parts 210/211 (Relative Spatial Location and Global Positioning), OPC-10030 (ISA-95 Common Model) with OPC-10031-4 Job Control V1/V2, OPC 30270 / OPC UA for Asset Administration Shell V2 and V3, OPC 10100-1 (WoT Connectivity), Part 200 (Industrial Automation), OPC 40001-1/-2/-3/-4/-101 (Machinery with Process Values, Job Management, Energy and Result Transfer), OPC 34100 (Energy Consumption Management), OPC 30081 (PA-DIM), OPC 40010-1 (Robotics), OPC 40100-1/-2 (Machine Vision control and asset management), OPC 40223 (Pumps and Vacuum Pumps), OPC 40200 (Weighing Technology) with OPC 30050 (PackML).
  • Modern developer surface — first-class Microsoft.Extensions.DependencyInjection hosting (services.AddOpcUa()), fluent server + client builders, source-generated NodeManagers and DataTypes, and an MCP server so LLMs / Copilot can drive an OPC UA client.

For the full feature breakdown see OPC UA Profiles and Facets and the What's New in 2.0 tour.

🚀 Getting started

To run a first OPC UA client and server, from NuGet packages or from the samples in this repository, follow Getting started. The documentation index then leads from the core concepts to advanced and experimental features.

You need the .NET 10 SDK to build the repo. From the repository root:

dotnet restore UA.slnx
dotnet build UA.slnx

For the supported target frameworks and platform notes see the Developer Guide. The official NuGet packages are published to nuget.org under the OPCFoundation.NetStandard prefix — the meta package OPCFoundation.NetStandard.Opc.Ua pulls in everything, or reference individual packages directly, e.g. OPCFoundation.NetStandard.Opc.Ua.Client for clients or OPCFoundation.NetStandard.Opc.Ua.Server for servers. Preview builds from every successful master build are available from the GitHub Packages NuGet feed, which is the only feed they are published to. nuget.org receives a version only through a manually approved promotion from a release/<major>.<minor> branch — that is where the 2.0.0-preview.N packages already on nuget.org came from, via the earlier release/2.0.0 line. To use those, enable prerelease packages and float with 2.0.0-preview.* until 2.0.0 is released. The XRegistry, WoT Connectivity, Robotics, Redundancy, Positioning, OpenUSD, and AI package families, the Vision.OpenUsd renderer, and the Robotics MCP extension remain preview packages when the root version is promoted to a stable version, and keep their own -preview.N versions on nuget.org. The Vision and MachineVision model/client/server packages and the Vision MCP package follow the root version without a preview-only override; development builds still inherit the root prerelease version. See docs/ReleaseProcess.md for how and when stable versions are released.

Samples

The stack also includes a large collection of platform-independent sample applications that turn its core services and companion models into runnable client/server workflows. More applications, including platform-specific examples, are available in the companion OPC UA .NET Samples repository.

Developer tools

  • OPC UA MCP Server — installable .NET tool and container exposing OPC UA client operations to LLMs and Copilot. Embeddable libraries provide Part 4 services, PubSub, diagnostics, Robotics and Vision, plus industrial companion profiles for AMB, Machinery, Scales, Pumps, Device Integration, ISA-95 and Positioning. The WoT and xRegistry profiles add asset/registry management and bounded document validation, planning and NodeSet conversion. Stack workflow profiles provide GDS/credential issuance, roles/users, files, alarms, history, schemas, and host-authorized PubSub and live WoT execution.

🔧 Migrating from 1.5.378 to 2.0

The 2.0 release introduces breaking API changes, and comes with a full prescriptive migration guide that links to per-area documentation for the migration sub-topics.

Most of the mechanical migration work is automated:

  • OPCFoundation.NetStandard.Opc.Ua.MigrationAnalyzer NuGet — install it in your project to get 26 analyzer rules through UA0030 (excluding UA0013, UA0016, UA0017, and the shim-only UA0029) plus one-click code fixes for the patterns in the guide. Setup steps are in the package's NugetREADME.md.
  • Migration agent skill — the opcua-v20-migration skill walks Copilot / Claude / any coding agent through installing the NuGet, running dotnet format analyzers to apply auto-fixes, and handling the small residual manual patterns. The skill knows which sub-doc to load for each symptom so it stays context-efficient.

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

If you are still on 1.x and not ready to upgrade, stay on the master378 branch — it continues to receive security and critical-bug fixes.

🤝 Contributing and license

Community contributions are welcome. Fork the repository, make your changes on a branch, and open a pull request; see CONTRIBUTING.md for the contribution workflow.

Contributors must sign the OPC Foundation Contributor License Agreement (CLA). The CLA "I AGREE" gate is presented automatically on your first PR.

The project is licensed under the OPC Foundation MIT License. Report security vulnerabilities via the process documented in SECURITY.md.

📚 Further reading

S
Description
OPC Unified Architecture .NET Standard
Readme 338 MiB
Languages
C# 99.3%
PowerShell 0.3%