Files
UA-.NETStandard/docs/NativeAoT.md
5899354441 Clarify documentation, migration guidance, and SDK selection (#4823)
# Description

Remove stock phrasing and correct misleading or inconsistent technical
documentation. The initial two passes covered 367 Markdown files,
followed by an interactive review of 169 editorial flags. The U5
interpretation originally deferred in that review has since received the
upstream Mantis answer recorded by #4843; remaining server/spec
follow-ups stay explicit in the CTT log.

- Correct package responsibilities, migration steps, API names,
ownership, protocol descriptions and links. Keep bundled migration
guides synchronized. Preserve historical conclusions as historical
records with separate re-check notes.
- Provide at least two rendered TOC levels throughout `docs/`. Convert
appropriate architecture figures to Mermaid without changing code
examples, transcripts or historical quotations.
- Address the October 19 feedback with concrete setup/migration
instructions, corrected certificate paths and PubSub names, shorter
repeated caveats, consistent XML comments, and a full review of the
Concepts guide. Retain #4839's API corrections.
- Integrate #4841's runtime/performance guidance and review
incoming/recent prose. Preserve dated measurements rather than claiming
new benchmark runs; clarify allocation ratios, startup-only processor
settings, JIT warm-up and the benchmark commit's scope. Missing raw
measurement artifacts and repeat ranges remain tracked by #4842.
- Merge master through `e8c5d800a` in `32c6394b7`. Resolve the CTT log
conflict using the updated Mantis states and OPC answers, retaining
historical framing and re-checks for C28/C32/C43.
- Address the latest naming/index feedback in `adb5bf693`: rename the
guides to `docs/WotCon.md` and `docs/WotNodeSetConversion.md`; move the
provider and DataType-declaration contracts into the conversion guide
and remove `docs/WoT.md`. Rename `samples/DI` to `samples/Di` and
`samples/Isa95` to `samples/ISA95`. Add content-index READMEs to Di,
FluentApi, ISA95, Lds and PubSub; update solution entries, project
references, Docker/CI paths, test fixture paths and documentation links
with exact casing.

**WoT guide scope.** This branch retains the detailed conversion guide
that #4758 had replaced with an anchor stub. Conversion limits, verified
document sets, preservation rules and provider ownership now live
together in `WotNodeSetConversion.md`; binding/runtime guidance remains
in `WotBindings.md` and `WotCon.md`. The design-rationale/test-ledger
prose was shortened, the oversized argument-table cell moved into its
section, and existing anchors preserved.

**SDK policy is a separate, explicit user-directed change.**
`global.json` sets a stable minimum of `10.0.400`, `rollForward:
latestMajor`, and `allowPrerelease: false`. Newer major SDKs are
permitted; CI's explicit SDK pins are unchanged. README, GettingStarted,
DeveloperGuide and Recycling instructions reflect the possible analyzer
differences. The image-contract regression fix accepts compatible stable
SDK images instead of requiring exact equality with the floor.

The latest four rename/index threads are resolved after publication.
Three older threads remain open: universal obsolete-removal timing,
unconditional nonce-strength wording, and a blanket Vision NativeAOT
claim. Existing implementation/evidence constraints are explained in
their inline replies. The two-level TOCs remain as requested.

## Validation

- `git diff --check` and staged diff checks: passed. The untouched
upstream AutoID NodeSet retains its provenance bytes, including two
existing license-header trailing spaces.
- `.\.azurepipelines\validate-migration-plugin.ps1`: passed; 15 bundled
migration documents and manifests synchronized.
- Documentation/path validation: **101** documents retain two rendered
TOC levels (**2,228** entries), with idempotent formatting. **52** new
relative links and their anchors passed exact-case checks. No tracked
references to the old guide/sample paths remain. Both relocated
provider-contract sections are preserved in the destination.
- `dotnet sln UA.slnx list`: passed; shows the renamed Di/ISA95 projects
and the existing FluentApi/Lds/PubSub projects. Updated solution and
pump ProjectReference paths also passed exact-case existence checks.
- Latest focused commands, run from the repository root:

```powershell
# Passed: 61 channel send-order and reconnect tests.
dotnet test tests\Opc.Ua.Core.Tests\Opc.Ua.Core.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~UaSCBinaryChannelSendOrderTests|FullyQualifiedName~TcpReconnectKeyAgreementTests' --verbosity minimal

# Passed: 5 pump datasheet tests; builds the renamed pump sample.
dotnet test tests\Opc.Ua.Di.Tests\Opc.Ua.Di.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~PumpDatasheetConformanceTests' --verbosity minimal

# Passed: 4 repository NodeSet path/round-trip tests, including the moved pump models.
dotnet test tests\Opc.Ua.Types.Tests\Opc.Ua.Types.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~RepositorySourceSurvivesSerializedLinkedPartitionsAsync' --verbosity minimal

# Passed: build, zero warnings/errors.
dotnet build samples\ISA95\MinimalIsa95Server\MinimalIsa95Server.csproj -p:CustomTestTarget=net10.0 -f net10.0 --verbosity minimal

# Passed: dependent sample-test project build, zero warnings/errors.
dotnet build tests\Opc.Ua.WotCon.Samples.Tests\Opc.Ua.WotCon.Samples.Tests.csproj -p:CustomTestTarget=net10.0 -f net10.0 --verbosity minimal
```

Earlier focused integration checks passed 2,620 tests across AutoID,
event queues/scheduling, source generation, MCP/package profiles and
WoT. Both reviewed Mermaid diagrams rendered locally without network
access. These checks are not a full solution run.

The full solution has **not** been rerun for this review. Earlier
`dotnet test UA.slnx -p:CustomTestTarget=net10.0 --verbosity quiet` did
not pass: three AOT projects rejected VSTest and 20 Vision tests failed
during graphics initialization with `OutOfMemoryException`. Remaining
long-running tests were stopped at the user's request. A focused Vision
rerun passed 558 tests and reproduced those 20 failures. The earlier
`dotnet test UA.slnx -p:CustomTestTarget=net48 --verbosity quiet` was
blocked by the former SDK pin and was not retried after the policy
change. The user approved proceeding with those limitations documented;
current remote CI is not claimed green.

## Related Issues

- Follow-up #4842 tracks the requested 2.0.2+ benchmark/tuning and
diagnostic-tool documentation refresh. #4841 supplies documentation and
earlier results, not all newly requested measurements.
- #4758 explains the conversion guide's earlier consolidation; the
current provider contracts are now consolidated into
`WotNodeSetConversion.md`.
- #4839 supplies the reviewed API corrections; #4843 supplies the
updated CTT issue record.
- The original prose cleanup and SDK policy were user-requested without
a source issue. No new runtime architecture is introduced by these
documentation edits.

## Checklist

_Put an `x` in the boxes that apply. You can complete these step by step
after opening the PR._

- [ ] 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.
- [ ] 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.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

---------

Co-authored-by: Roman Ettlinger <romanett98@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:10:55 +02:00

15 KiB

Native AOT

Native AOT (ahead-of-time) compilation publishes an application and the parts of the SDK that it uses as a single native executable. The executable starts quickly and runs without an installed .NET runtime, but it supports only code that the compiler can analyze at publish time. This guide first shows how to publish an application, then describes the test harness that verifies the stack under Native AOT.

Contents

Publish an application

Enable Native AOT

Install the native toolchain for your platform. Then set PublishAot in the application's project file:

<PropertyGroup>
  <OutputType>Exe</OutputType>
  <TargetFramework>net10.0</TargetFramework>
  <PublishAot>true</PublishAot>
</PropertyGroup>

The stack's Native AOT tests run on net10.0. dotnet build and dotnet run still use the JIT compiler; only dotnet publish compiles the native executable.

Publish and verify the executable

Publish for the runtime identifier of the target platform, such as win-x64, linux-x64, linux-arm64, or osx-arm64:

dotnet publish -c Release -r win-x64

The bin/Release/net10.0/<runtime-identifier>/publish folder then contains one native executable and its symbol file. If the folder instead contains the application's .dll and coreclr.dll, the publish did not use Native AOT. Check that PublishAot applies to the target framework you publish, delete the bin and obj folders, and publish again.

The client and server from Getting started publish this way without trim or AOT warnings. A published application is also a new instance for its certificate stores when PkiRoot depends on the working directory, as in Getting started. Run it from the folder that contains its pki folder, or trust its new certificate again.

Use AOT-compatible features

Fix every trim and AOT warning (IL2026, IL3050, and related codes) that the publish reports for your code. The following features are AOT-compatible:

In your own code, avoid unbounded reflection and runtime code generation; see Keep code AOT-compatible.

Clients and servers run in globalization-invariant mode, which the InvariantGlobalization property enables to make native executables smaller. In this mode a server still selects translations by locale id and falls back to another region of the same language. Arguments in translated texts, such as numbers and dates, use the invariant format for every locale.

Test harness overview

The Opc.Ua.Aot.Tests project verifies that the core OPC UA libraries work correctly when published as a Native AOT binary. The tests cover:

  • Encoding, sessions, subscriptions, and monitored items.
  • Discovery, security, events, and history.
  • Diagnostics, batch operations, and the node cache.
  • Complex types, GDS client operations, and client sample patterns.

All tests run inside a single ahead-of-time compiled executable.

The crypto provider model is AOT-compatible and covered by CryptoProviderAotTests; see CryptoProvider. The optional OPCFoundation.NetStandard.Opc.Ua.Security.Pkcs11 package is covered too, by Pkcs11AotTests: although Pkcs11Interop carries no trim or AOT annotations of its own, the ILCompiler analysis produces no warnings for the paths the package uses, so it is marked IsAotCompatible on net10.0. Resolving the token module is native interop, which trimming does not affect.

Prerequisites

.NET SDK

  • .NET 10.0 SDK (or later LTS) is required.

Platform-Specific Native Toolchain

Native AOT compilation requires a C/C++ toolchain on the build machine.

Platform Requirement
Windows Visual Studio 2022+ with the Desktop development with C++ workload, or the equivalent Build Tools package.
Linux clang and zlib1g-dev (Debian/Ubuntu) or the equivalent packages for your distribution.
macOS Xcode Command Line Tools (xcode-select --install).

See the official Microsoft documentation for full details: https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?tabs=windows%2Cnet8plus

Project Structure

tests/Opc.Ua.Aot.Tests/
├── Opc.Ua.Aot.Tests.csproj   # Project file (PublishAot=true, net10.0)
├── AotServerFixture.cs        # Lightweight AOT-compatible server host
├── AotTestFixture.cs          # Shared fixture: starts server + client session
├── GdsTestFixture.cs          # GDS-specific test fixture
├── EncodingAotTests.cs        # Binary & JSON encoding round-trips
├── DataTypeAotTests.cs        # OPC UA data type verification
├── SessionAotTests.cs         # Session lifecycle & reconnect
├── SubscriptionAotTests.cs    # Subscription create / modify / delete
├── MonitoredItemAotTests.cs   # Monitored item operations
├── DiscoveryAotTests.cs       # Endpoint & server discovery
├── SecurityAotTests.cs        # Security policy negotiation
├── EventsAotTests.cs          # Event subscription & filtering
├── HistoryAotTests.cs         # Historical read operations
├── DiagnosticsAotTests.cs     # Server diagnostics
├── BatchOperationsAotTests.cs # Batch read / write / call
├── NodeCacheAotTests.cs       # Client-side node cache
├── ComplexTypeAotTests.cs     # Complex type loading & serialization
├── GdsClientAotTests.cs       # Global Discovery Server client
├── ClientSamplesAotTests.cs   # End-to-end client sample patterns
├── AotClientSamples.cs        # Helper methods for client samples
├── PubSubAotTests.cs          # Part 14 PubSub publisher / subscriber round-trips
├── WebApiAotFixture.cs        # Kestrel host for REST endpoint round-trips
├── WebApiAotTests.cs          # REST binding (Opc.Ua.Bindings.Https) smoke + Basic auth
└── StubWebApiServer.cs        # IWebApiServer stub backing WebApiAotFixture

Why TUnit Instead of NUnit?

The project uses the TUnit test framework instead of NUnit. TUnit generates test-discovery code at compile time, so this test binary can be published with Native AOT. The repository's NUnit test projects use runtime reflection for discovery instead and are not the Native AOT test path.

Test Fixture Pattern

AotTestFixture implements IAsyncInitializer and IAsyncDisposable from TUnit. It is shared across all test classes via the attribute:

[ClassDataSource<AotTestFixture>(Shared = SharedType.PerTestSession)]

On initialization the fixture:

  1. Starts a ReferenceServer in-process using AotServerFixture<T>.
  2. Creates a client ApplicationConfiguration programmatically.
  3. Connects an ISession to the server over opc.tcp.

Every test class receives the fixture through its primary constructor and reuses the same server and session, keeping the test suite fast.

AotServerFixture<T> is a cut-down, AOT-compatible version of ServerFixture<T> from the NUnit test infrastructure. It avoids transitive references to BenchmarkDotNet, Moq, and other packages that are not AOT-friendly.

How to Build and Run

1. Publish the Native AOT Binary

dotnet publish tests/Opc.Ua.Aot.Tests/Opc.Ua.Aot.Tests.csproj --configuration Release

The publish step compiles the entire application (tests, server, and all referenced OPC UA libraries) into a single native executable. This can take several minutes depending on the machine.

2. Run the Tests

Windows (x64):

./tests/Opc.Ua.Aot.Tests/bin/Release/net10.0/win-x64/publish/Opc.Ua.Aot.Tests.exe

Linux (x64):

./tests/Opc.Ua.Aot.Tests/bin/Release/net10.0/linux-x64/publish/Opc.Ua.Aot.Tests

The executable discovers and runs all tests, producing TUnit console output and writing results to a TestResults directory.

Build + Run in a Single Step (Development)

For iterative development you can combine both commands:

# Windows
dotnet publish tests/Opc.Ua.Aot.Tests/Opc.Ua.Aot.Tests.csproj -c Release && ^
  tests\Opc.Ua.Aot.Tests\bin\Release\net10.0\win-x64\publish\Opc.Ua.Aot.Tests.exe

# Linux / macOS
dotnet publish tests/Opc.Ua.Aot.Tests/Opc.Ua.Aot.Tests.csproj -c Release && \
  ./tests/Opc.Ua.Aot.Tests/bin/Release/net10.0/linux-x64/publish/Opc.Ua.Aot.Tests

Note: dotnet test and dotnet run do not perform AOT compilation. You must use dotnet publish followed by direct execution of the resulting binary.

CI Integration

The GitHub Actions workflow .github/workflows/buildandtest.yml runs AOT jobs on Ubuntu and both Intel and ARM64 macOS; the weekly .github/workflows/nightly.yml run adds Windows. Each platform performs these steps:

  1. Checkout the repository.
  2. Setup .NET 10.0 SDK.
  3. Publish the project with dotnet publish in Release configuration.
  4. Execute the platform-specific binary directly.
  5. Publish + execute the .Historian and .Mcp companions the same way, keeping results separate.
  6. Upload any TestResults artifacts.

The job runs in a separate matrix from the main dotnet test build so that AOT failures are isolated and clearly visible.

Writing New AOT Tests

1. Choose or Create a Test Class

Place AOT tests in tests/Opc.Ua.Aot.Tests/. Each file should focus on a single area (encoding, sessions, etc.). Apply the shared fixture:

[ClassDataSource<AotTestFixture>(Shared = SharedType.PerTestSession)]
public class MyFeatureAotTests(AotTestFixture fixture)
{
    [Test]
    public async Task MyTestAsync()
    {
        // Use fixture.Session, fixture.ServerUrl, etc.
        await Assert.That(fixture.Session.Connected).IsTrue();
    }
}

2. Use TUnit Attributes and Assertions

  • Mark tests with [Test] (not NUnit's [Test]—they are different types).
  • Use await Assert.That(…) for assertions. TUnit assertions are async.
  • Do not reference NUnit, xUnit, or MSTest assemblies.

3. Keep Code AOT-Compatible

  • Avoid unbounded reflection. Do not use Type.GetType(), Activator.CreateInstance(), or similar APIs unless the types are statically reachable.
  • Avoid dynamic code generation. Reflection.Emit, System.Linq.Expressions.Expression.Compile(), and similar APIs are not supported.
  • Prefer concrete generic instantiations. The trimmer must see every generic type combination at compile time.
  • Annotate when necessary. Use [DynamicallyAccessedMembers] to declare reflection requirements or [DynamicDependency] to preserve specific dependencies. [RequiresUnreferencedCode] declares trimming incompatibility and warns callers; it does not preserve metadata or make code trim-safe.

4. Handle Trimming Warnings

The project suppresses IL2104 (see the .csproj), which comes from third-party packages that are not yet trim-annotated. For warnings in your own code, fix the root cause rather than suppressing.

Troubleshooting

'vswhere.exe' is not recognized on Windows

The native link step locates the Visual C++ tools with vswhere.exe. If the publish fails with 'vswhere.exe' is not recognized as an internal or external command, add the Visual Studio Installer folder to PATH and publish again:

$env:PATH = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer;$env:PATH"
dotnet publish -c Release -r win-x64

Publish Fails with Linker Errors

Ensure the platform-specific C/C++ toolchain is installed (see Prerequisites). On Windows, verify the Desktop development with C++ workload is present in the Visual Studio Installer.

TypeInitializationException or MissingMetadataException at Runtime

The IL trimmer removed type metadata that is needed at runtime. Common fixes:

  • Add [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] to parameters or fields that hold types accessed via reflection.
  • Add an explicit rd.xml file or [DynamicDependency] attribute to preserve specific types.
  • Ensure the type is statically referenced somewhere in the code path.

Tests Pass Under dotnet test but Fail Under AOT

dotnet test runs with JIT and full reflection. Some APIs silently work under JIT but are unsupported in AOT. Compare the stack trace from the AOT binary to identify which API is problematic, then refactor to a trim-safe alternative.

Slow Publish Times

Native AOT compilation is inherently slower than JIT builds because it performs whole-program optimization. On CI this is expected. For local development, consider running the NUnit tests with dotnet test for fast feedback, and reserve AOT publish for final validation.

IL2104 or Other Trimming Warnings

Warnings prefixed with IL come from the IL trimmer/linker. The project suppresses IL2104 for third-party packages. If you see new warnings from OPC UA code, investigate and fix the root cause. Suppress only as a last resort and document the reason in a code comment.