Skip to content

Client: fewer allocations per request (shared timeout timer, pooled state machines, fewer buffer collections) - #4849

Merged
marcschier merged 9 commits into
masterfrom
romanett/client-request-alloc
Oct 20, 2026
Merged

marcschier merged 9 commits into
masterfrom
romanett/client-request-alloc

Conversation

@romanett

@romanett romanett commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Reduces client allocations per request. A client GC investigation found that a gen0 pause on the request path costs about 1.1 ms however much survives. That makes the number of collections, and therefore the bytes allocated per request, what matters. At the default gen0 budget, each KB removed from a request removes about one collection in eight.

Read-1 client bytes/request (perf/ServerLoadHarness run --scenario read --nodes 1 --sessions 20, builds run alternately, 3–4 rounds each, medians). Bytes/op repeated within ±5 B between rounds, while req/s varied 3x from other load on the machine, so throughput is not reported.

Commit Change classic managed
master 484596c 1983 –
77e2ca0 One timeout timer per client channel instead of an ITimer per request 1871 –
730cec1 BinaryDecoder returns Array.Empty<T>() for zero-length arrays (empty StringTable/DiagnosticInfos in every response header); -1 still decodes as null 1817 1913
2135f7d SealSymmetricMessage secures the encoded chunks in place instead of copying them into a second BufferCollection 1750 1839
70655ff A response that is a single final chunk is decoded from the chunk directly, without saving it into a BufferCollection 1675 1767
8edf352 ChannelAsyncOperation is its own IValueTaskSource (no CompletionWaiter) and locks itself (no Lock) 1599 1686
4528d04 ManagedSession releases its reader lock from a pooled state machine (.NET 6+) instead of a second task continuation 1598 1598
41859b6 UaSCUaBinaryClientChannel.SendRequestAsync uses PoolingAsyncValueTaskMethodBuilder (.NET 6+), like TcpByteTransport 1426 1425
b3d0980 Review: no request admitted after Dispose; ChannelAsyncOperation keeps its private Lock again (DeveloperGuide: never expose locks) 1472 –
71ec7b3 Review: return []; for empty arrays – –

In total: classic 1983 → 1472 B (−26 %). The managed client gets the same ~49 B back from the restored Lock.

What reviewers should look at

  • Timeouts: each operation records a deadline. The channel keeps one timer set for the earliest pending deadline. When it fires it times out every request whose deadline has passed and re-arms for the next. The operation is added to m_requests before it schedules its deadline, and the scan resets the scheduled time under the same lock, so no new request is missed. With equal timeouts a new request is never the earliest, so it only reads the scheduled time. The public ChannelAsyncOperation constructors still create a timer of their own.
  • Dispose of the client channel now fails the pending requests with BadSecureChannelClosed. Without a timer per request they would otherwise never complete. Requests are registered under the timeout lock and rejected once the channel is disposed, so a request racing Dispose is either rejected or drained.
  • Pooled value tasks: the value tasks from SendRequestAsync and from ManagedSession service calls must now be awaited once. Awaiting one twice used to happen to work because they were backed by a task. WaitForCompletionAsync was already documented as one wait at a time.
  • Not done here (needs generator or codec API work): reusing the BinaryEncoder/BinaryDecoder objects (~200 B), pooling the generated SessionClient.ReadAsync box (~195 B), and the second ResponseHeader per response.

Related Issues

  • No issue. Follow-up of the client GC investigation.

Checklist

  • I have signed the CLA and read the CONTRIBUTING doc.
  • I have added tests that prove my fix is effective or that my feature works and increased code coverage.
    • PendingOperationsTimeOutAtTheirOwnDeadlinesAsync (two deadlines on one FakeTimeProvider)
    • RequestAfterDisposeFailsInsteadOfWaitingAsync, RequestsRacingDisposeAllCompleteAsync
    • ReadZeroLengthArraysReturnsEmptyWithoutAllocating
  • 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.
    • net10.0: Core 6450, Core.Encoders 2947, Types 13928, Client 3226 passed. One Client test (SessionBindingLiveTests "incarnation") timed out once while the benchmarks were loading the machine and passed when its fixture was rerun alone (96/0). net48: Opc.Ua.Client and its dependencies build clean; net48 tests not run locally.
  • I fixed all failing and flaky tests in the CI pipelines and all CodeQL warnings.
  • I have addressed all PR feedback received.

🤖 Generated with Claude Code

romanett and others added 7 commits October 19, 2026 13:36
Every request created an ITimer for its timeout (TimerQueueTimer +
SystemTimeProviderTimer), ~113 B of the ~1.98 KB a Read-1 request
allocates on the client. The operation now records its deadline and the
client channel keeps one timer armed for the earliest deadline among its
pending requests; the scan times out the expired ones with
BadRequestTimeout and re-arms for the next. With equal timeouts a new
request never moves the earliest deadline, so it only reads it under a
lock.

Dispose faults the requests still pending with BadSecureChannelClosed,
since without the channel's timer they would no longer time out.

ServerLoadHarness read --nodes 1 (20 sessions, 4 alternating rounds):
client allocB/op 1983 -> 1871.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ReadArrayElements and ReadFixedWidthArray allocated a new T[0] for a
zero-length array, which every response header has (StringTable,
DiagnosticInfos). A length of -1 still decodes as a null array.

ServerLoadHarness read --nodes 1 (20 sessions, 4 alternating rounds):
client allocB/op 1871 -> 1822 on top of the channel timer change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SealSymmetricMessage copied the encoded chunks into a second
BufferCollection. The chunks are now replaced in place by the segments
to send, which are over the same buffers, so the encoded collection is
the one sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tion

A final chunk was saved into a new BufferCollection and taken back out
even when it was the whole response. When no chunks of the message are
saved, the partial message is open and the chunk is within the limits,
the response is now decoded from the chunk directly and its buffer
returned afterwards; anything else takes the saved-chunks path as
before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
WaitForCompletionAsync allocated a CompletionWaiter per wait, and every
operation allocated a Lock. The operation now implements IValueTaskSource
itself (it is waited for at most once, which is how the client channel
uses it) and locks itself; CA2002 is suppressed for the file because
nothing else locks an operation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ExitReaderOnCompletion registered the release as a continuation on the
service call's task, so the caller's await was the second continuation
and allocated the task's continuation list (~80 B per request). On .NET 6
and later the call is awaited in a pooled state machine that releases the
lock before its own result completes; net48 keeps the continuation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every request allocated the async state machine box of
UaSCUaBinaryClientChannel.SendRequestAsync (~170 B). On .NET 6 and later
it uses PoolingAsyncValueTaskMethodBuilder, like the transport's send and
receive; the callers await the returned task once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings October 19, 2026 14:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Concurrent disposal and request registration can leave finite-timeout requests waiting indefinitely.

2 open issues
What changed in this PR

Reduces client request allocations across transport handling, decoding, and managed-session coordination.

Changes:

  • Shares request timeout scheduling through one channel timer.
  • Removes intermediate buffer collections and empty-array allocations.
  • Uses allocation-saving completion sources and pooled async state machines.
File Description
tests/​Opc.Ua.Types.Tests/​Encoders/​BinaryDecoderTests.cs Tests shared empty arrays and null preservation.
tests/​Opc.Ua.Core.Tests/​Stack/​Transport/​UaSCBinaryClientChannelDeterministicTests.cs Tests independent deadlines with the shared timer.
src/​Opc.Ua.Types/​Encoders/​BinaryDecoder.cs Reuses empty arrays during decoding.
src/​Opc.Ua.Core/​Stack/​Tcp/​UaSCBinaryClientChannel.cs Shares timeout scheduling, pools requests, and streamlines response decoding.
src/​Opc.Ua.Core/​Stack/​Tcp/​UaSCBinaryChannel.Symmetric.cs Secures chunks in the existing collection.
src/​Opc.Ua.Core/​Stack/​Tcp/​UaSCBinaryChannel.cs Adds single-chunk detection and timerless operations.
src/​Opc.Ua.Core/​Stack/​Tcp/​ChannelAsyncOperation.cs Embeds completion state and changes synchronization.
src/​Opc.Ua.Client/​Utils/​AsyncReaderWriterLock.cs Pools reader-lock release state machines on modern .NET.

Review effort: Balanced

romanett and others added 2 commits October 19, 2026 16:54
…private Lock

Review feedback on #4849:
- Dispose stopped the timeout timer and failed the requests it found, but
  a request registered concurrently could be added after that snapshot
  and, with the timer gone, wait forever. Registration now happens under
  the timeout lock and is rejected with BadSecureChannelClosed once the
  channel is disposed, so every admitted request is in the drain. Tests
  for a request after Dispose and for requests racing Dispose (both hang
  without the fix).
- ChannelAsyncOperation is public and inheritable, so lock (this) exposed
  its lock (docs/DeveloperGuide.md: never expose locks, use
  System.Threading.Lock). The private Lock is back; this costs ~49 B per
  request (read --nodes 1: 1423 -> 1472 B).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review feedback on #4849: return [] instead of Array.Empty<T>(); for an
array return type it is the same shared instance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Code coverage

✅ Coverage gate passed.

Check Result Threshold
✅ Project line rate 89.45% (374650/418854 lines) >= 70.00%
✅ Project branch rate 79.99% >= 60.00%
✅ Patch coverage 96.09% (123/128 changed lines) >= 75.00% (> 100 changed lines)
ℹ️ Baseline delta (advisory) +15.85 pp 73.60% recorded
Uncovered changed lines
  • src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs: 1715, 1716, 1717, 1786
  • src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs: 836

Coverage is above the recorded baseline - consider ratcheting coverage-thresholds.json.

Thresholds live in coverage-thresholds.json. Whole report before exclusions: line 88.72%, branch 79.23%.

@codecov

codecov Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.40625% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.79%. Comparing base (484596c) to head (71ec7b3).
⚠️ Report is 10 commits behind head on master.

Files with missing lines Patch % Lines
...c/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs 88.05% 4 Missing and 4 partials ⚠️
src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs 77.77% 1 Missing and 1 partial ⚠️
src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs 97.61% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4849      +/-   ##
==========================================
+ Coverage   83.72%   83.79%   +0.06%     
==========================================
  Files        2832     2881      +49     
  Lines      413951   418854    +4903     
  Branches    72083    73031     +948     
==========================================
+ Hits       346596   350971    +4375     
- Misses      43708    44010     +302     
- Partials    23647    23873     +226     
Flag Coverage Δ
actions 83.79% <91.40%> (+0.06%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/Opc.Ua.Client/Utils/AsyncReaderWriterLock.cs 95.45% <100.00%> (ø)
...c.Ua.Core/Stack/Tcp/UaSCBinaryChannel.Symmetric.cs 88.46% <100.00%> (-0.03%) ⬇️
src/Opc.Ua.Types/Encoders/BinaryDecoder.cs 87.35% <100.00%> (-0.05%) ⬇️
src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs 70.75% <97.61%> (+0.56%) ⬆️
src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs 86.31% <77.77%> (+0.02%) ⬆️
...c/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs 68.16% <88.05%> (+3.59%) ⬆️

... and 124 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@marcschier
marcschier merged commit 6a156df into master Oct 20, 2026
207 of 209 checks passed
@marcschier
marcschier deleted the romanett/client-request-alloc branch October 20, 2026 03:16
romanett added a commit that referenced this pull request Oct 20, 2026
#4849 added two synchronous Assert.ThrowsAsync calls after the NUnit 5
migration (#4840), where ThrowsAsync returns a Task; master and every
branch merged from it fail to build Opc.Ua.Core.Tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
marcschier added a commit that referenced this pull request Oct 21, 2026
# Description

A follow-up to #4825. It adds
`AutoIdClient.RefreshDeviceAsync(AutoIdDeviceSnapshot,
CancellationToken)`, which reads the variables of a reader device that
change at runtime again through the NodeIds a snapshot already carries.
It makes one Read and no Browse.

## Why

`ReadDeviceAsync` browses the children of the device on every call. OPC
30010 makes most device variables and methods optional, so the browse is
how the client finds out what this device publishes.
`AutoIdReadOptions.StatusOnly` only narrows the Read. This is the point
the Copilot review raised on #4825
([discussion](#4825 (comment))).
1458af9 documented the behaviour, but a client that polls the status
of N readers still pays N Browse and N Read requests per cycle. One Read
per reader would do.

`AutoIdDeviceSnapshot` already carries what a poll needs:
`DeviceStatusId`, `LastScanDataId`, `LastScanTimestampId`,
`DeviceLocationId` and `Methods`, all taken from that browse.
`RefreshDeviceAsync` uses them.

## Change

- **`RefreshDeviceAsync(snapshot)`** reads `DeviceStatus` and, when the
device publishes them, `LastScanData`, `LastScanTimestamp` and
`DeviceLocation`. That is one Read of one to four variables and no
Browse. It returns a copy of the snapshot (`with`), and every other
member, including `Methods` and the NodeIds, is unchanged.
- **Stateless.** The client keeps no cache. The caller holds the
snapshot, as with the other companion clients
(`PumpsClient.ReadPumpAsync`, `ScalesClient.ReadSnapshotAsync`, and
Robotics' `RefreshAsync` on its handles). A poller calls
`ReadDeviceAsync` once and then passes the snapshot to
`RefreshDeviceAsync` on every cycle.
- **Stale snapshot.** The snapshot is not validated against the server.
If it no longer matches the device (the device or a variable was
deleted, or the server assigned other NodeIds after a restart), the
status of the Read surfaces:
- a bad status for `DeviceStatus` (for example `BadNodeIdUnknown`) is
thrown as `ServiceResultException` with that status;
- a bad status for `LastScanData` is returned in `LastScanStatus` with a
null value;
- a bad `LastScanTimestamp` or `DeviceLocation` leaves that member at
its default.

In each case the caller reads the device again with `ReadDeviceAsync`.
That also picks up optional variables and methods the device published
after the snapshot was taken.
- **Arguments.** A null snapshot throws `ArgumentNullException`. A
snapshot without a `DeviceStatus` NodeId (not obtained from
`ReadDeviceAsync`) throws `ArgumentException`. Neither one makes a
service call.
- **Docs.** Covered in the XML docs of `ReadDeviceAsync`,
`RefreshDeviceAsync`, `AutoIdReadOptions` and `AutoIdDeviceSnapshot`, in
`docs/AutoID.md` and in the client `NugetREADME.md`. The wording
maintainers gave `AutoIdReadOptions` in 1458af9 stays as it is, with
one added sentence that points to `RefreshDeviceAsync`. `docs/AutoID.md`
states the cost of each call:

| Call | Network cost |
| --- | --- |
| `ReadDeviceAsync(reader)` | One Browse of the device's children
(BrowseNext only if the server pages the result), one Read of every
published variable |
| `ReadDeviceAsync(reader, AutoIdReadOptions.StatusOnly)` | One Browse,
one Read of two variables (`DeviceStatus`, `DeviceName`) |
| `RefreshDeviceAsync(snapshot)` | One Read of up to four variables, no
Browse |

The change is additive. No existing member changes behaviour, and there
are no new dependencies. The MCP `autoid_read_device` tool still uses
`ReadDeviceAsync`, because a single MCP tool call has no snapshot to
refresh.

## Tests

`tests/Opc.Ua.AutoID.Tests`:

- `AutoIdRefreshDeviceTests` (new, 7 tests) uses a `MockBehavior.Strict`
`ISession` with `VerifyNoOtherCalls`, so any Browse, BrowseNext or
second Read fails the test:
- one Read of exactly the four snapshot NodeIds (Value attribute,
`maxAge` 0), with the values mapped and the other members (`Methods`,
`DeviceName`, NodeIds) unchanged;
- a device without the optional variables is refreshed with a
one-variable Read;
- a stale `DeviceStatus` NodeId throws with the Read's status
(`BadNodeIdUnknown`);
- a stale `LastScanData` surfaces `BadNodeIdUnknown` in
`LastScanStatus`, and a bad timestamp or location resets those members;
  - a result-count mismatch throws `BadUnexpectedError`;
  - null and invalid snapshots are rejected without a service call;
  - cancellation reaches the Read.
- `AutoIdReaderEndToEndTests` (2 new tests against the hosted AutoID
server over opc.tcp):
- `ARefreshedSnapshotCarriesTheCurrentStatusAsync`: a reader is read
once, then faulted on the server. The refreshed snapshot shows `Error`
and the methods from the original browse.
- `ARefreshOfAStaleSnapshotSurfacesTheStatusOfTheReadAsync`: snapshots
whose NodeIds the server does not know (as after a deletion).
`LastScanStatus` carries `BadNodeIdUnknown`, and an unknown
`DeviceStatus` NodeId throws `BadNodeIdUnknown`.
- **Fail-without (mutation checks):**
- With a Browse of the device's children added to `RefreshDeviceAsync`,
every strict-mock test that reaches the Read fails.
- With a bad `LastScanData` status masked to `BadNotFound` (the
`ReadDeviceAsync` convention for optional variables),
`AStaleOptionalVariableSurfacesItsStatusWithoutThrowingAsync` and the
end-to-end stale-snapshot test fail.
  - Without the method, the tests do not compile.

## Verification (local, macOS arm64, SDK 10.0.402 from `global.json`)

Head 2118c24 on OPCFoundation/master ac24123 (#4852), which includes
the NUnit 5 migration (#4840). The new tests follow the NUnit 5
conventions in `docs/DeveloperGuide.md`: `Assert.ThrowsAsync` and
`Assert.MultipleAsync` are awaited, and the enclosing test returns
`Task`.

- `Opc.Ua.AutoID.Tests` on net10.0: 315 passed, 0 failed (9 of them
new).
- `Opc.Ua.AutoID.Tests` builds with `-p:CustomTestTarget=net48` with 0
warnings and 0 errors. Running net48 needs Windows, so the fork CI
covers it.
- `dotnet format` whitespace, style and analyzers at `--severity info`,
verify-no-changes on the changed `.cs` files: no findings in the new
code.
The branch is based on OPCFoundation/master `ac24123dd` (#4852, the last
master commit with a green build). Fork CI was not repeated on this
head: earlier fork runs of this branch failed only in test projects
outside this PR (the master build was broken by the NUnit 5 migration
#4840 and fixed in #4852; master is currently broken again in
`Opc.Ua.Core.Tests` by #4849). The upstream checks of this PR test it
against the current master.

## Related Issues

- Follow-up to #4825 (tracking issue #4824). Resolves the polling-cost
point of the Copilot review on `AutoIdReadOptions` in #4825.
- #4823 (open) edits prose in other sections of `docs/AutoID.md`. There
is no textual overlap with the client section changed here.

## Checklist

- [x] 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.
- [x] 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. (Local build of the changed projects: 0 warnings, 0
errors.)
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed. (Locally
the AutoID test project on net10.0; net48 is built but runs only on
Windows CI.)
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings. (Pending the upstream checks; see the CI note
above.)
- [x] I have addressed **all** PR feedback received.

---------

Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
marcschier added a commit that referenced this pull request Oct 21, 2026
…be a component of a machine (#4853)

# Description

Follow-up to the AutoID companion (#4825). Two changes to where the
AutoID server places its readers:

1. **`IAutoIdReaderBuilder.WithParent` is made conformant with OPC
10000-100 4.9.** Until now it placed a reader below another node
*instead of* `DeviceSet`, and the docs suggested "a component of a
machine" as the use case. A machine in the Machinery `Machines` folder
is not reachable from `DeviceSet`, so such a reader could not be located
from `DeviceSet`, which DI 4.9 requires for every `ComponentType`
instance (every AutoID device type derives from DI `DeviceType`). Now
the reader is still placed below the parent (`HasComponent`, unchanged),
and:
- when `DeviceSet` already reaches the parent through hierarchical
references (for example another reader, or any device it organizes),
nothing else is added: the reader is a component of a composed device
and DI 4.9 wants "only the root instance" referenced from `DeviceSet`;
- otherwise `DeviceSet` also organizes the reader (`Organizes`, both
directions), so it stays locatable.
2. **New opt-in `IAutoIdReaderBuilder.AsComponentOf(BaseObjectState
machine)`**, available only when AutoID is composed with Machinery
(`AddAutoIdToMachinery`, or a DI owner that loads the Machinery model).
It makes the reader an identifiable component of the machine per OPC
40001-1 11:
- the reader is placed below the machine's `Components` add-in
(`HasComponent`, as `MachineComponentsType` declares for `<Component>`);
- it gets the `2:Identification` add-in (`HasAddIn`) typed
`MachineryComponentIdentificationType`, which holds no copies: it
references the reader's own DI nameplate properties with `HasProperty`
(`Manufacturer`, `SerialNumber`, and those of `Model`,
`ManufacturerUri`, `ProductCode`, `HardwareRevision`,
`SoftwareRevision`, `DeviceRevision`, `DeviceClass`,
`ProductInstanceUri` that are set, plus `AssetId`/`ComponentName` when
published; `DeviceManual` and `RevisionCounter` are left out as 40001-1
10.2 recommends);
- the reader stays a device: the same `DeviceSet` rule as for
`WithParent` applies with `Components` as the parent, so in the usual
case (a machine in `Machines` that `DeviceSet` does not reach)
`DeviceSet` organizes it directly. It is not added to `Machines`.
- Checked before anything is registered, each failing with
`Bad_ConfigurationError` and a message naming the way out: the server
has no Machinery model (names `AddAutoIdToMachinery`), the machine is
not a node of the AutoID owner, the machine has no `Components` add-in
(names `WithComponents`), or the reader nameplate lacks `Manufacturer`
and/or `SerialNumber` (mandatory in `MachineryItemIdentificationType`).
`WithParent` and `AsComponentOf` exclude each other
(`InvalidOperationException`).

Default behaviour is unchanged: a reader built without
`WithParent`/`AsComponentOf` is organized by `DeviceSet` and not added
to `Machines`. Rollback on failure covers the new references: a failed
build removes the `DeviceSet` reference, the component and its add-in,
so the name can be used again.

## Specification basis

| Statement | Source |
| --- | --- |
| "The DeviceSet Object is the starting point to locate Devices. It
shall either directly or indirectly reference all instances of a subtype
of ComponentType with a Hierarchical Reference. For complex Devices that
are composed of various components that are also Devices, only the root
instance shall be referenced from the DeviceSet Object. The components
of such complex Devices shall be locatable by following Hierarchical
References from the root instance." | OPC 10000-100 (DI) 1.05.0, 4.9 |
| AutoID device types are "Subtype of DeviceType defined in OPC
10000-100". OPC 30010 does not mention `DeviceSet`, Machinery or
`Machines`. | OPC 30010 (AutoID) 1.01, 6.1 Table 7 |
| "Each Machine providing this building block provides the Components
Object, which directly references all identifiable components of a
Machine." / "Note: That does not preclude that a Machine is organizing
its components in various other hierarchies as well." | OPC 40001-1
(Machinery) 1.04.2, 11.1 |
| "The MachineComponentsType provides HasComponent References to all
identifiable components of a Machine"; Table 27: `0:HasComponent Object
<Component> 0:BaseObjectType OP`; Table 28: `<Component> 0:HasAddIn
Object 2:Identification MachineryItemIdentificationType M`; "As all
identifiable components shall contain the Identification Object". | OPC
40001-1 1.04.2, 11.2 |
| `MachineryItemIdentificationType`: `2:Manufacturer` M,
`2:SerialNumber` M, all other members O. | OPC 40001-1 1.04.2, 8.3 Table
16 |
| `MachineryComponentIdentificationType` is the component subtype of
`MachineryItemIdentificationType` (adds `2:DeviceRevision`); "It is not
recommended to use the optional Properties 2:RevisionCounter and
2:DeviceManual"; a missing component `2:ProductInstanceUri` "shall be
omitted". | OPC 40001-1 1.04.2, 10.2 |
| "it is recommended to keep this approach and let several References
lead to the same Node, rather than duplicating the Node" / Robotics
example: identification Properties "are only referenced from the
Identification functional group". | OPC 40001-1 1.04.2, 7.3 and Annex
B.2 (informative) |
| "It is expected that domain-specific companion specifications using
this specification will define what assets of the domain in what usage
are considered to be Machines or components of Machines." | OPC 40001-1
1.04.2, 11.1 (Note) |
| Organizes "can be used to span multiple hierarchies"; more than one
hierarchical path to a Node is allowed. | OPC 10000-3 1.05, 7.11, 7.5 |

**SDK decisions** (not specified by OPC 30010, which predates
Machinery):

- A reader is never added to `Machines`: no specification classifies an
AutoID device as a machine (40001-1 11.1 leaves that to the domain
specifications, AutoID is silent).
- A reader becomes a component of a machine only when the application
asks for it (`AsComponentOf`).
- `WithParent` keeps its parent and adds the `DeviceSet` reference
rather than rejecting parents outside `DeviceSet` (see below).
- The component `Identification` references the reader's nameplate
instead of copying it.
- AutoID does not add Machinery conformance units; the Machinery owner
advertises them for what its builders created.

### Why `WithParent` adds a reference instead of rejecting

DI 4.9 asks for reachability, not for a particular parent, and OPC
10000-3 allows several hierarchical paths to one node. Adding
`Organizes` from `DeviceSet` satisfies the "shall" while keeping the
parent the application asked for, and it is the same reference type
`DeviceSet` already uses for every reader (and the DI node manager for
every device). Rejecting such parents with `Bad_ConfigurationError`
would break existing callers that hang a reader below a machine or
folder. When `DeviceSet` already reaches the parent, no reference is
added, so the "only the root instance" rule of 4.9 holds for composed
devices. Reachability is decided once when the reader is built, by
following the forward hierarchical references of the owner's nodes.

### Why `AsComponentOf` keeps the reader referenced from `DeviceSet`

Machinery does not require machines to be in `DeviceSet` (the stock
builders put them in `Machines` only), so a reader that is only below
`Components` would again be unreachable from `DeviceSet`. The same
reachability rule as for `WithParent` applies: if the machine is itself
reachable from `DeviceSet` (for example a machine that is also a DI
device organized by `DeviceSet`), the reader is reached through it and
gets no direct reference, otherwise `DeviceSet` organizes it.

### Shape of `AsComponentOf`

It takes the machine's `BaseObjectState`, like `WithParent(NodeState)`
and `IMachineryBuildContext.BindMachine(TState, ...)`; with the stock
builders that is `IMachineHandle<TState>.State`. It requires the
machine's `Components` add-in to exist
(`IMachineBuilder.WithComponents`, or a companion-declared one bound
with `WithComponents(components, ...)`) instead of creating one, so the
Machinery builders stay the only place that creates Machinery building
blocks (`MachineryBuildingBlocks` organization, facets). The reader's
NodeState parent is the `Components` object, so the DI node manager
attaches it with `HasComponent` and the existing registration and
rollback code applies unchanged.

## Behaviour change for existing callers

- `WithParent(parent)` with a parent that `DeviceSet` does not reach
(for example a machine in `Machines`, or an application folder): the
reader is now *also* browsable from `DeviceSet` (one extra `Organizes`
reference, both directions), and an
`AutoIdClient.EnumerateReadersAsync()` (which browses `DeviceSet`) now
finds it. Its parent, NodeId and `HasComponent` reference are unchanged.
- `WithParent(parent)` with a parent `DeviceSet` reaches (for example
another reader): unchanged.
- Default placement: unchanged.
- `IAutoIdReaderBuilder` gains a member. The interface is implemented
only inside the package (instances come from `AutoIdRuntime.Reader`),
and the package is new in 2.0.

## Changes

- `src/Opc.Ua.AutoID.Server/AutoIdReaderPlacement.cs` (new, internal):
`DeviceSet` lookup, the reachability check, the `Organizes` reference
and its removal, `Components` resolution and validation, the nameplate
check, and the `Identification` add-in.
- `src/Opc.Ua.AutoID.Server/AutoIdRuntime.cs`: the builder's nameplate
delegate runs once (validated before anything is registered, then copied
into the DI builder); `AsComponentOf` resolves `Components` as the
parent before the device is created; after registration the add-in is
added and the `DeviceSet` reference kept; rollback removes the
reference.
- `src/Opc.Ua.AutoID.Server/Builders/IAutoIdReaderBuilder.cs`,
`AutoIdReaderBuilder.cs`: `AsComponentOf`, mutual exclusion with
`WithParent`, XML docs stating the exact behaviour.
- `docs/AutoID.md`: new "Placement" subsection under "Hosting readers"
(what DI 4.9 and Machinery 11 require, what is an SDK decision, a table
per builder call, an example), the composition table rows for readers
and `Machines`, the test fixture table.
`src/Opc.Ua.AutoID.Server/NugetREADME.md`: a short paragraph.
- Tests (below).

## Tests

- `AutoIdReaderLifecycleTests` (stand-alone owner):
`ReadersCanHangBelowAnExplicitParentAsync` now also asserts that
`DeviceSet` does not organize a reader below another reader;
`AReaderBelowAParentOutsideTheDeviceSetIsStillOrganizedByItAsync`;
`AFailedCreationBelowAnOutsideParentLeavesNoDeviceSetReferenceAsync`
(rollback); `AStandaloneReaderCannotBeAComponentOfAMachineAsync`
(`Bad_ConfigurationError` naming `AddAutoIdToMachinery`); argument
checks for `AsComponentOf(null)` and both call orders of
`WithParent`/`AsComponentOf`.
- `AutoIdCompositionTests` (Machinery owner, in process):
`AReaderBecomesAComponentOfAMachineAndStaysADeviceAsync` (parent is
`Components`, `HasComponent`, `DeviceSet` organizes it, `Machines` does
not, `Identification` with `HasAddIn` and the component type,
`HasProperty` to the reader's own `Manufacturer`/`SerialNumber`/`Model`
nodes, no `DeviceManual`, owned subtree);
`AComponentNeedsAMachineWithComponentsAndRegistersNothingOtherwiseAsync`;
`AComponentNeedsTheMandatoryIdentificationAsync`;
`AComponentNeedsAMachineOfTheOwnerAsync`;
`AFailedComponentCreationIsRolledBackAsync`.
- `AutoIdPlacementEndToEndTests` (new, hosted Machinery + AutoID over a
real session): a default reader, a reader below that reader, a reader
`AsComponentOf` a machine and a reader `WithParent` the machine.
Browsing `DeviceSet` finds the three roots and not the nested reader,
the outer reader reaches the nested one;
`MachineryClient.DiscoverMachinesAsync` returns only the machine and
`Machines` contains no reader;
`MachineryClient.EnumerateComponentsAsync` lists only the component
reader, `ReadIdentificationAsync` reads `Manufacturer`, `SerialNumber`,
`ProductCode` through the add-in, which is `HasAddIn`-referenced and
typed `MachineryComponentIdentificationType` and whose `HasProperty`
targets are the reader's own nameplate nodes;
`AutoIdClient.EnumerateReadersAsync` finds the three roots.
- The existing default assertions
(`TheReadersShareTheDeviceSetWithThePumpAndStayOutOfTheMachinesFolderAsync`,
`TheMachineryAndPumpsClientsStillFindTheirInstancesAsync`,
`ComposedReadersLiveBelowTheSharedDeviceSetAsync`) are unchanged.
- Fail-without: with the runtime wiring reverted to master (builder
surface kept so the tests compile), 10 of the new tests fail: all
`AsComponentOf` cases, both `WithParent` cases outside `DeviceSet` and
the three session tests that look for the component or the extra
`DeviceSet` reference. Removing only the rollback of the `DeviceSet`
reference makes both rollback tests fail. `NoReaderBecomesAMachineAsync`
and the existing default tests pass with and without the change, as
intended.

Local results (macOS arm64, SDK 10.0.402, head `238ed9b69` on master
`9bfc780e1`; the same three commits are now based on master `ac24123dd`
as `c6d70909b`, no AutoID file changed in between):
`Opc.Ua.AutoID.Tests` net10.0 318/318 passed; `Opc.Ua.AutoID.Server` all
TFMs and the test project with `CustomTestTarget=net48` build with 0
warnings, 0 errors (net48 tests run on Windows CI; there is no mono host
here). `dotnet format whitespace/style/analyzers --verify-no-changes` on
the changed files: no new findings beyond the conventions of the
surrounding test files.

## Commits

1. `fix(autoid): keep every reader reachable from DeviceSet`
2. `feat(autoid): make a reader a component of a machine`
3. `docs(autoid): document where readers are placed`

The branch is based on OPCFoundation/master `ac24123dd` (#4852, the last
master commit with a green build). Fork CI was not repeated on this
head: earlier fork runs of this branch failed only in test projects
outside this PR (the master build was broken by the NUnit 5 migration
#4840 and fixed in #4852; master is currently broken again in
`Opc.Ua.Core.Tests` by #4849). The upstream checks of this PR test it
against the current master.

## Related Issues

- Follow-up to #4825 (tracking issue #4824).
- #4823 (open) edits prose in other paragraphs of `docs/AutoID.md`
(table of contents, the DI-owner paragraph, providers). This PR adds a
subsection and changes two rows of the composition table and one row of
the test table; no hunk overlaps. The table of contents is deliberately
not touched here because #4823 adds the subsection entries for "Hosting
readers"; the "Placement" entry can be added there or after both are
merged.

## Checklist

- [x] 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.
- [x] 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. (Local build of the changed projects: 0 warnings, 0
errors.)
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed. (Locally
the AutoID test project on net10.0; net48 is built but runs only on
Windows CI.)
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings. (Pending the upstream checks; see the CI note
above.)
- [x] I have addressed **all** PR feedback received.

---------

Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
marcschier pushed a commit that referenced this pull request Oct 21, 2026
## Problem
A client request that lives across a GC is promoted. Publish requests
always are: they wait at the server for the publishing interval. When
the response arrives, two **dead** old objects still reference it:

1. `UaSCUaBinaryChannel.WriteOperation.MessageBody`:
`UaSCUaBinaryClientChannel.SendRequestAsync` read it but never cleared
it.
2. The box of the generated `SessionClient.*Async` method. It is `async
ValueTask<T>` with the default builder, so a call that completes
asynchronously leaves a `Task<T>` box holding the result and the hoisted
`response` locals.

The GC treats old objects as live. Every gen0 and gen1 collection
therefore keeps the whole response alive through the card table until a
full collection. With 100k monitored items, every `PublishResponse` (100
`MonitoredItemNotification`s) ended up promoted to gen2.

Evidence (ClrMD scan of a live client dump, 25 sessions × 40
subscriptions × 100 items): 1,073 KB of gen0 was kept only by dead old
objects, against 136 KB kept by live ones. The dead holders were exactly
the two above, holding the same responses. Gen2 held 37 MB of dead
notifications.

## Change
- `SendRequestAsync` clears `operation.MessageBody` once it has read the
response.
- `ClientApiTemplates`: generated `SessionClient` async methods use
`PoolingAsyncValueTaskMethodBuilder` on .NET 6+. A completed box resets
its result and state machine. This is the same pattern #4849 applied to
the channel and `ManagedSession`.

Contract note: the generated `SessionClient` calls now return pooled
value tasks, so each must be awaited once, like any value task. All
sync-over-async call sites in the repo use `.AsTask()` first.

After the fix, young data kept only by dead old objects is 0 KB (was
1,073 KB).

## Measurements
`perf/ServerLoadHarness`, client `client-gc:` line. Master vs this
branch, 3 alternating rounds, runs gated on foreign CPU load (shared
machine). Ranges are over the rounds.

| scenario | build | pause share | GC p50 ms | survived/gen0 |
survived/gen1 | gen2 MB | B/op |
|---|---|---|---|---|---|---|---|
| sub 100k items (25×40×100, pub 500 ms) | master | 4.9–5.4 % | 7.9–8.2
| 2.28–2.57 MB | 1.4–1.7 MB | 121–123 | 235–238 |
| | this PR | 4.0–4.5 % | 6.1–6.9 | 0.64–0.71 MB | 0.19 MB | 86 |
233–240 |
| sub 50k items (25×20×100) | master | 1.7–2.2 % | 5.5–6.5 | 2.1–2.2 MB
| 0.8–1.1 MB | 56–62 | 233–238 |
| | this PR | 1.7–1.8 % | 5.2–5.5 | 0.39–0.41 MB | 0.1–0.2 MB | 44–49 |
232 |
| read 1 node, 200 sessions | master | 8.9–9.2 % | 2.2–2.4 | 200 KB | |
20 | 1456 |
| | this PR | 7.3–7.7 % | 2.2–2.7 | 113–163 KB | | 20 | 1272 |
| read 1 node, 20 sessions | master | 3.3–3.6 % | 0.9–1.2 | 50–53 KB | |
4.4 | 1456 |
| | this PR | 2.8–2.9 % | 0.85–1.16 | 32–46 KB | | 4.4 | 1272 |

The first fix round at 100k ran while another process starved the server
(46k notif/s); it is left out of the fix row.

- At 50k items, gen1 collections drop from 15 to 1 per 10 s.
- GC phases at 100k items (TraceAnalyzer `gc`): card marking 3.3 → 2.55
ms (2.8 → 0.72 MB marked), plan+relocate+compact 6.05 → 3.27 ms.
- Allocation: −184 B per request (−12.6 %), because the `Task` box per
call is gone.

## Tests
net10.0: Opc.Ua.Client.Tests 3283 passed / 0 failed, Opc.Ua.Core.Tests
6535/0, Opc.Ua.SourceGeneration.Core.Tests 4412/0, Opc.Ua.Sessions.Tests
857/0. The net48 Release build of Opc.Ua.Client (with Core) is clean.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants