Skip to content

Server: pool the Read result arrays until the response is sent (R2) - #5207

Merged
marcschier merged 3 commits into
masterfrom
romanett/r2-read-result-pooling-69f87e
Nov 28, 2026
Merged

marcschier merged 3 commits into
masterfrom
romanett/r2-read-result-pooling-69f87e

Conversation

@romanett

Copy link
Copy Markdown
Contributor

Proposed changes

Pool the per-request result storage of the server Read service (R2 of the publish/write load work). The pooled storage is the DataValue[] results, the ServiceResult[] operation errors and the per-request attribute Dictionary<NodeId, Variant[]>. The arrays go back to the pool only after the transport has encoded or dropped the response.

  • Pooled buffer. ReadResultBuffer (new, Opc.Ua.Server/NodeManager) holds the arrays and the dictionary. It reuses the D5 PooledNotificationBuffer<T> bucket pool (16..4096 entries, at most 1024 buffers / 16 MiB per bucket). A request larger than the biggest bucket gets an exact buffer that is not retained.
  • Release point. StandardServer answers with an internal PooledReadResponse : ReadResponse (same pattern as LeasedPublishResponse). Its ReuseCore() clears Results and returns the buffer once. Transports call IPooledEncodeable.Reuse() only after encode or drop. Clone() copies the values and owns no buffer. A response that is never reused (an in-process caller, say) leaves its buffer to the GC.
  • Node managers get fixed-count IList views of exactly the request's length, because a rented array is larger and node managers may size by values.Count.
  • Failure paths. The buffer is returned and cleared on any exception (parameter validation, response budget, cancellation, a node manager throwing). The errors array and the attribute dictionary are cleared as soon as the dispatch finishes.
  • Not pooled. A server whose MasterNodeManager.ReadAsync is overridden, or that uses its own IMasterNodeManager, keeps the exact-array path, because an override may hold on to the results. The check is AOT-safe and falls back to "not pooled".
  • The dictionary is pooled, not made lazy. It is passed non-null into public GetPermissionMetadataAsync, and null there means "permissions only".

No public API changes. MasterNodeManager.ReadAsync still returns exact arrays.

Measurements

Paired A/B, read with 20 sessions × 100 nodes, 6 rounds. The base is 826dadcaa, which already includes #5193.

Metric Base R2 Change
Bytes per request 19,954 13,960 −30.0 % (all 12 runs)
CPU per request 211.6 µs 211.0 µs −0.3 %
Values/s 7.51 M 7.38 M −1.7 % (server cores −1.4 %, within drift)
GC pause per 15 s, default GC 404 ms 399 ms flat
GC pause per 15 s, DATAS off (4 rounds) 54 ms 39 ms −27 % (gen0 96 → 66)

With default settings the DATAS GC shrinks the gen0 budget as allocation drops, so the collection count and the pause stay flat. Lock contention went from about 500 to 820 events per 15 s against roughly 1.1 M requests, probably from the pool's queues.

Tests

  • New ReadResultBufferTests: values survive encoding after the buffer is returned and its arrays are overwritten. Also covers a single return on a double Reuse, Clone, the list semantics, dispatch-state clearing, and oversized requests.
  • New AsyncCustomNodeManagerTests.ReadPooling (all three node manager types): the pooled read matches an exact read. The buffer is returned on a mid-read failure (BadResponseTooLarge), on rejected parameters or a wrong buffer size, and on cancellation. Overridden ReadAsync is not pooled.
  • New ReadResultPoolingServerTests: ReferenceServer reads go through the pool, then encode, Reuse and decode across rounds.
  • Local runs on net10.0: Server.Tests passed 12,529. The 9 failures are file-system tests outside the Read path (8 need symlink privilege, 1 hit a teardown file lock). Client.Tests passed 3,998 with 2 skipped. The new tests also pass on net48.

Types of changes

  • Enhancement (non-breaking change which adds functionality)

Checklist

  • I have read the CONTRIBUTING doc.
  • I have added tests that prove my fix is effective or that my feature works.

🤖 Generated with Claude Code

The Read service allocated a DataValue[] for the response, a ServiceResult[]
for the operation results and a permission-attribute Dictionary per request.
StandardServer now rents all three from a pooled ReadResultBuffer
(PooledNotificationBuffer buckets) and answers with a PooledReadResponse whose
Results are a slice of the buffer. The transports call Reuse() once the
response has been encoded or dropped (as for LeasedPublishResponse), which
clears and returns the buffer.

- Node managers get fixed-length IList views of exactly the request's count,
  so code that sizes by values.Count is unaffected by the larger pooled arrays.
- The operation results and attribute cache are cleared as soon as the
  dispatch ends; the buffer is returned when the read fails (validation,
  response budget, cancellation, node manager exception).
- Pooling is only used when MasterNodeManager.ReadAsync is not overridden; an
  override (or a custom IMasterNodeManager) keeps the exact-array path, since
  it may keep the results. MasterNodeManager.ReadAsync and the public
  response types are unchanged.
- A response that is never reused (mutator replaced it, in-process caller)
  leaves its buffer to the GC; Clone() copies the values.

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

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

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

The public ReadResponse.MemberwiseClone() bypasses ownership-aware cloning and shares the buffer, allowing reuse to clear the original response’s results and return the same buffer twice, corrupting another request.

1 open issue

Review effort: Balanced

The generated ReadResponse.MemberwiseClone is public and non-virtual, so a
copy made through a ReadResponse reference bypassed the Clone override and
shared the buffer reference. Reusing that copy returned the buffer and
cleared the original's results, and reusing the original returned it again.
The response now remembers itself as the owner, and a copy only drops its
reference.

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

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Code coverage

✅ Coverage gate passed.

Check Result Threshold
✅ Project line rate 89.50% (514859/575258 lines) >= 70.00%
✅ Project branch rate 80.14% >= 60.00%
✅ Patch coverage 93.67% (207/221 changed lines) >= 75.00% (> 100 changed lines)
ℹ️ Baseline delta (advisory) +15.90 pp 73.60% recorded
Uncovered changed lines
  • src/Opc.Ua.Server/NodeManager/MasterNodeManager.ServiceDispatch.cs: 433, 435
  • src/Opc.Ua.Server/Subscription/PooledNotificationBuffer.cs: 174
  • src/Opc.Ua.Server/Server/StandardServer.cs: 1443, 1445, 1446
  • src/Opc.Ua.Server/NodeManager/ReadResultBuffer.cs: 185, 195, 196, 198, 200, 204, 214, 219

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

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

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.

🔵 Needs a closer look

The clone path redundantly copies results already copied by base.Clone(), doubling request-sized result-array allocation and copying for every cloned response.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Low severity Avoid cloning Results twice

src/​Opc.Ua.Server/​NodeManager/​ReadResultBuffer.cs:281

base.Clone() already copies Results through the generated ReadResponse.MemberwiseClone() and CoreUtils.Clone(ArrayOf<DataValue>). Copying the original results again here allocates a second request-sized array and immediately discards the first one, doubling result-array allocation and copying for every cloned response. Keep the results produced by the base clone and only remove its buffer ownership.

1 resolved since last review

Review effort: Balanced

…onse

The generated ReadResponse.MemberwiseClone already deep-copies Results, so
the second copy in PooledReadResponse.Clone only allocated a request-sized
array to throw away the first one.

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

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.

🟢 Approval recommended

The read-result pooling changes have no active review issues.

No open issues 🎉

Review effort: Balanced

@codecov

codecov Bot commented Nov 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.21267% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.85%. Comparing base (826dadc) to head (0551484).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
src/Opc.Ua.Server/NodeManager/ReadResultBuffer.cs 87.50% 8 Missing ⚠️
src/Opc.Ua.Server/Server/StandardServer.cs 90.62% 3 Missing ⚠️
...r/NodeManager/MasterNodeManager.ServiceDispatch.cs 88.88% 2 Missing ⚠️
...Ua.Server/Subscription/PooledNotificationBuffer.cs 60.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #5207      +/-   ##
==========================================
- Coverage   83.87%   83.85%   -0.02%     
==========================================
  Files        3875     3876       +1     
  Lines      575085   575258     +173     
  Branches    99135    99153      +18     
==========================================
+ Hits       482355   482390      +35     
- Misses      60072    60177     +105     
- Partials    32658    32691      +33     
Flag Coverage Δ
actions 83.85% <93.21%> (-0.02%) ⬇️

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

Files with missing lines Coverage Δ
...Server/NodeManager/NodeManagerServiceDispatcher.cs 86.44% <100.00%> (+0.09%) ⬆️
...r/NodeManager/MasterNodeManager.ServiceDispatch.cs 81.88% <88.88%> (+0.34%) ⬆️
...Ua.Server/Subscription/PooledNotificationBuffer.cs 96.29% <60.00%> (-3.71%) ⬇️
src/Opc.Ua.Server/Server/StandardServer.cs 90.55% <90.62%> (-0.87%) ⬇️
src/Opc.Ua.Server/NodeManager/ReadResultBuffer.cs 87.50% <87.50%> (ø)

... and 63 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 4db695e into master Nov 28, 2026
144 checks passed
@marcschier
marcschier deleted the romanett/r2-read-result-pooling-69f87e branch November 28, 2026 19:23
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