Repository navigation
Description
Summary
Remove most of the remaining per-request allocations on the hot path of simple services (Read, Write, Browse, Call), on the server and on the client. Requests and responses are pooled or kept short-lived, generated messages stop allocating default headers they discard, and the per-request pipeline objects are merged or pooled. The encoder and decoder per message are tracked separately in #4871.
The targets are about 10 objects and under 1 KB per single-value Read on the server, and under 1 KB on the client. There is no change on the wire.
This is roadmap item A2 of the o6-automation benchmark gap analysis. This issue lists only what remains on master (1b01996, 2026-12-02). Already done and removed from this issue: #4805, #4812, #4856, #4847/#4849, #4870 (client ReadAsync state machine box), #4982 (server AsyncLocal request scopes), #5118 (no NodeHandle per node on Read and Write for node managers with the default lookup), #5183 (no quadratic per-request NamespaceDefaultPermissions[]), #5207 (pooled Read result arrays) and #5078 (client writer started inline).
Status
| Item | Status |
|---|---|
Server: work item and closure per write batch in UaSCUaBinaryChannel |
Partly done. The writer is started with a static delegate through ThreadPool.UnsafeQueueUserWorkItem, but the server write path still allocates a work item and a closure per write batch (3.7 %, see below). |
| 1. Lazy structure fields in generated types | Open |
2. Pooled request/response messages, client RequestHeader reuse |
Open. Read result arrays are pooled (#5207); the PooledReadResponse object itself, and Write, Browse and Call, are not. |
3. One per-request object instead of OperationContext + RequestLifetime (+ CancellationTokenSource) + EndpointIncomingRequest |
Open |
4. FairRequestQueue.Entry, per-request namespace default cache, ServerSystemContext copy, client WriteOperation |
Open |
| 5. Server Browse allocation regression since 87cf16d (+35–50 %) | New, see below |
Current state
Measured 2026-12-02 with perf/ServerLoadHarness: managed client, 20 sessions, reference server node managers (simulation on), .NET 10, --duration 15 --warmup 8, 24 logical processors. Both builds ran back to back on the same machine; master figures are the range of 5 runs, 87cf16d (the 2026-11-13 state this issue was last measured at) of 2 runs. Bytes per request are deterministic except Browse on master (see below). Background allocation (--baseline 5) is now about 3.2 MB/s on the server and changes the master figures by under 0.5 %.
| Scenario | Server, bytes per request: 87cf16d → master | Client, bytes per request: 87cf16d → master |
|---|---|---|
read --nodes 1 |
2,323–2,325 → 2,055–2,061 (−11 %) | 1,270–1,273 → 1,232–1,233 (−3 %) |
read --nodes 100 |
52,664–52,685 → 13,957–13,993 (−73 %) | 7,606–7,607 → 5,985–5,988 (−21 %) |
browse |
33,450–33,463 → 44,267–50,600 (+35–50 %) | 6,478–6,505 → 6,096–6,113 (−6 %) |
The server's Read 100 drop comes from #5118, #5183 and #5207. Browse is a regression; see "Server Browse regression" below.
Server: what a single-value Read still allocates
Sampled allocation ticks on master 1b01996, share of bytes, first Opc.Ua frame. Read the shares as a ranking: the sampler over-weights small objects. The reference server's background simulation is now under 0.5 % of the samples.
| Source | Share |
|---|---|
Request pipeline objects: OperationContext (from SessionManager.ValidateRequestAsync) 15.8 %, RequestLifetime 4.9 % with its CancellationTokenSource 2.4 %, EndpointIncomingRequest 3.6 % |
26.7 % |
FairRequestQueue.Entry (TryEnqueue) 10.3 %, plus OwnerQueue, its dictionary node, Lock and QueueNode from FairRequestQueue.Link 1.7 % |
12.0 % |
Codec objects per message: BinaryDecoder 6.8 %, BinaryEncoder 4.3 %, BufferCollection 3.8 % and ArraySegment<byte>[] 1.6 % from ArraySegmentStream.GetBuffers, encoder Byte[] 1.8 % (tracked in #4871) |
18.3 % |
Per-request namespace default cache: StrongBox<NamespaceDefaultPermissions> 3.8 % and StrongBox<NamespaceDefaultPermissions>[] 2.9 % (NamespaceDefaultPermissionReader.ReadAsync) |
6.7 % |
Discarded default RequestHeader allocated in TcpTransportListener.OnRequestProcessed, where the generated Reuse() resets the request |
4.0 % |
Decoded values: Byte[] (ReadByteString) 2.6 % and ByteString (ReadNodeIdBody: opaque NodeIds, probably the authentication token) 1.6 % |
4.2 % |
Write path: a closure (<>c__DisplayClass219_0) attributed to UaSCUaBinaryChannel.RunWritesAsync 2.2 %, and the QueueUserWorkItemCallbackDefaultContext from TcpServerChannel.TrySendResponseWithoutGate starting the writer 1.5 % |
3.7 % |
ServerSystemContext copy per request (AsyncCustomNodeManager.ValidatePermissionsAsync) |
3.0 % |
Request/response objects: decoded RequestHeader 5.1 %, the response's ResponseHeader 5.2 %, ReadValueId 4.7 % and ReadValueId[] 1.6 %, PooledReadResponse 4.1 % |
20.7 % |
Client: what a single-value Read still allocates
| Source | Share |
|---|---|
Codec objects per message: BinaryDecoder 20.7 %, BinaryEncoder 19.3 % (tracked in #4871) |
40.0 % |
Pending-request tracking: WriteOperation 20.3 % and its dictionary node 0.2 % (UaSCUaBinaryClientChannel.BeginOperation) |
20.5 % |
RequestHeader built per call in SessionClient.ReadAsync |
19.0 % |
Decoded ResponseHeader |
19.8 % |
ReadRequest, ReadResponse, DataValue[], buffer collections |
< 1 % |
The discarded default ResponseHeader of the generated ReadResponse constructor (6.8 % on 2026-11-13) is down to 0.15 %, and the client's ArraySegment<byte>[]/BufferCollection are nearly gone.
Server Browse regression
Server bytes per Browse rose from 33.5 K (87cf16d) to 44.3–50.6 K on master, and the master figure is bimodal (about 44.3 K or 49.6–50.6 K per run). The client is unchanged. Top allocations on master (browse, server, first Opc.Ua frame):
| Source | Share |
|---|---|
ReferenceDescription (AsyncCustomNodeManager.GetReferenceDescriptionAsync) |
10.7 % |
LocalizedTextFormatAndTranslation 10.3 % and String 2.7 % from ResourceManager.Translate |
13.0 % |
ConcurrentDictionary<NodeId, byte> nodes 8.9 %, buckets 3.3 % and a lock Object 3.7 %, Int32[] 2.7 %, SemaphoreSlim 0.8 % in AsyncCustomNodeManager.BrowseAsync |
19.4 % |
NodeHandle (GetManagerHandleAsync 4.7 %, GetReferenceDescriptionAsync 1.0 %): Browse still takes the handle path |
5.6 % |
Permission checks per reference: PermissionReadSnapshot 3.2 %, ExecutionContext 2.0 % (ReadPermissionAwareAttributes), Dictionary<NodeId, PermissionType> 1.9 % with entries 2.7 % and a boxed PermissionType 0.8 % (MasterNodeManager.ValidateRolePermissions), RolePermissionType[]/clones/Func 3.6 %, ExtensionObject[] 6.1 % |
20.3 % |
NodeState.CaptureStoredReferences / PopulateBrowser: IReference[], NodeStateReference, lists |
13.4 % |
The per-browse ConcurrentDictionary, the ExecutionContext capture and the per-reference permission snapshot are the first suspects. The commit that introduced the increase has not been bisected yet.
Proposed changes
1. Generated messages: no discarded defaults (server and client)
The generated Initialize() (called from constructors, decoding and Reuse()) creates default instances of every structure-typed field, such as RequestHeader, ResponseHeader and DiagnosticInfo. The decoder or the service then replaces them. The server still allocates one discarded RequestHeader per request in Reuse() (4.0 %).
- Make structure-typed fields of generated types lazily initialized: null-backed with a property that materializes the default on first read, or decoded directly into the field.
- Check equality,
IsEqual,Clone, JSON/XML encoding andToStringagainst the lazy representation, so behaviour stays identical. - This is a source generator change for all generated types. A decode constructor alone breaks base classes generated by older generators, and a lazy getter alone breaks
IsEqualand hashing (noted in Server: cut request-path lock contention and allocation; add load harness #4707 and Client: cut per-request allocation and CPU in the channel and session; measure the client in the load harness #4720). - The server's response
Reuse()cannot simply be skipped: pooled publish responses release their notification lease inReuse(), and pooled Read responses return their result buffer there (Server: pool the Read result arrays until the response is sent (R2) #5207).
2. Pooled request and response messages
- Server: rent
ReadRequest/ReadResponse(and Write, Browse, Call) from a per-type pool when a request is handled synchronously on the receive loop. Return them after the response has been encoded and the request is complete.PooledReadResponse(Server: pool the Read result arrays until the response is sent (R2) #5207) already has the release point; the object itself is still allocated per request (4.1 %). - Handlers must not keep references to request or response objects beyond the call. That is an API contract change and needs a migration note, and possibly an opt-out: a server option, or per node manager.
- As a first step, pool the result collections of Write, Browse and Call the way Server: pool the Read result arrays until the response is sent (R2) #5207 does for Read.
- Client: reuse the
RequestHeaderper call, or build it lazily from the session's defaults, when the caller passes none (19 % of the client's bytes per Read).
3. Server request pipeline: one per-request object
- Merge
OperationContext,RequestLifetime(with itsCancellationTokenSource) andEndpointIncomingRequestinto one pooled per-request object, or create the cancellation source only when a timeout or cancellation is actually registered (together 26.7 % of the server's sampled bytes per Read). All three currently escape to public or protected APIs (RequestLifetimeis public,OperationContextis passed to node managers), so pooling needs an ownership contract like (2).
4. Remaining per-request bookkeeping
- Server:
FairRequestQueue.Entry(10.3 %). It is also the node of the lock-free FIFO and stays referenced after dispatch (Server: fewer allocations per single-value Read (isolation reservations, scope reuse, routing capture without restore) #4856), so pooling needs a different queue node or an epoch scheme. Shrinking it (fewer per-stage fields) is a smaller first step. The per-ownerOwnerQueuewith its dictionary node andLock(FairRequestQueue.Link, 1.7 %) also shows up per request in this load, so it is apparently unlinked and recreated between requests of the same session. - Server: the per-request namespace default cache (6.7 %). Server: cache static namespace defaults server-wide; O(1) per-request cache #5183 made it O(1), but a single-value Read still allocates the slot array and one
StrongBoxper namespace it touches. A hit in the server-wide static cache should not need a per-request entry. - Server: the
ServerSystemContextcopy per request (3.0 %), and the closure and work item per write batch inUaSCUaBinaryChannel(3.7 %). - Client: pool the pending
WriteOperationand its dictionary node inUaSCUaBinaryClientChannel.BeginOperation(20.5 % of the client's bytes per Read), keeping the exactly-once completion semantics (see the timeout scan from Client: fewer allocations per request (shared timeout timer, pooled state machines, fewer buffer collections) #4849).
5. Server Browse
- Find the change that raised Browse from 33.5 K to 44–51 K bytes per request and why the figure is bimodal, then fix it.
- Then Browse's own allocations: the per-browse
ConcurrentDictionaryand lock, the handle path (NodeHandle, as Server: cut node-lookup and permission-check allocations on Read and Write #5118 removed for Read and Write), and the permission check per returned reference.
Compatibility
- Wire format: unchanged.
- Public API:
- Generated types change from eager to lazy defaults (1). This is observable only through reference identity, so behaviour stays the same.
- The handler contract for pooled messages (2) and pooled per-request objects (3) is new: request, response and context objects must not be retained after the service call returns. That needs a
docs/MigrationGuide.mdentry and probably an opt-out.
- Behaviour: none intended. Diagnostics, auditing, cancellation and timeouts must behave as today.
Plan
Each step is independent and measurable on its own, and can be its own PR:
- Server Browse regression (5): bisect between 87cf16d and master and fix.
- Lazy structure fields in generated types (source generator, all generated types). Benefits server and client.
- Server pipeline: one per-request object instead of
OperationContext+RequestLifetime+EndpointIncomingRequest; cancellation source on demand. - Client: reusable
RequestHeaderand pooled pending operation. Together about 40 % of the client's sampled bytes per Read. - Server bookkeeping: queue entry and owner queue, namespace default cache, system context copy, write-batch closure.
- Pooled request/response messages (or Write/Browse/Call result collections first), behind an option, with a migration note.
The encoder and decoder per message, and the buffer collections, are tracked in #4871.
How to measure
- Harness:
perf/ServerLoadHarness(seeperf/README.md).- Scenarios:
read --nodes 1|100,write,browse,sub,--sessions 200;native-readwith the o6 workers for the server alone. - The result block reports bytes and CPU per request for the server (
per-op:) and the client (client-per-op:), and the client's collections (client-gc:). Bytes per request are deterministic and are the primary metric.--baseline <s>reports the same figures without the background allocation (per-op-net:); the per-PR allocation gate (perf: add a per-PR allocation gate (bytes/op, load-independent) #5203) checks those. - CPU per request: measure the server pinned to 4 cores (
--server-affinity 0xF,SERVER_DOTNET_PROCESSOR_COUNT=4). Throughput only as paired, alternating A/B runs (perf/ab.sh). - To build a pre-.NET-11-SDK commit such as 87cf16d with SDK 11 installed:
-p:RunAnalyzers=false -p:NoWarn=CA2027 -p:TreatWarningsAsErrors=false.
- Scenarios:
- Profiles:
--trace-profile allocwith--trace-side server|client, thenTraceAnalyzer allocfor the per-type breakdown;TraceAnalyzer gcfor collections and pauses. - Targets:
- server: about 10 objects and under 1 KB per single-value Read (now 2,055–2,061 B);
- client: under 1 KB per single-value Read (now 1,232–1,233 B);
- no regression for
read --nodes 100,browseand subscriptions; - fewer gen0 collections per request on both sides.
Activity
[-]Server: allocation-free request fast path (pooled messages, no default headers, per-channel codec reuse)[/-][+]Server and client: allocation-free request fast path (pooled messages, no default headers, per-channel codec reuse)[/+][-]Server and client: allocation-free request fast path (pooled messages, no default headers, per-channel codec reuse)[/-][+]Server and client: allocation-free request fast path (pooled messages, no default headers, no AsyncLocal scopes)[/+]