Skip to content

Client: keep available sequence numbers without a new array per response - #5024

Merged
marcschier merged 1 commit into
romanett/client-event-bytesfrom
romanett/client-gc-availability-cards
Nov 8, 2026
Merged

marcschier merged 1 commit into
romanett/client-event-bytesfrom
romanett/client-gc-availability-cards

Conversation

@romanett

@romanett romanett commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Stacked on #5005 (which now contains #5017). Part of #5003.

Problem

After #5017, the client under the events load still spends most of the measuring window in gen0 GC pauses, although only about 1 MB survives each collection. Most of each pause is mark older (cards) and plan+relocate+compact. Both walk the cards of old objects that point at young ones.

Every Publish response gave two long-lived objects a reference to a new array of available sequence numbers: the SubscriptionManager availability window and MessageProcessor.AvailableInRetransmissionQueue. Each of these writes dirties a card that the next collections walk.

Change

  • AvailabilityWindow copies the numbers into a fixed 16-entry array, or into its existing HashSet above 16 entries, instead of keeping the response's array.
  • AvailableInRetransmissionQueue is now a property backed by a reused array under a small lock. Reading it returns a copy. Readers are rare: gap handling, the not-dispatched set, and the subscription snapshot.

No behaviour change.

How it was found

An experiment build turned off three card sources one at a time, with two traced runs per toggle:

  • This one: the change shown here.
  • Linked cancellation source: reusing it per worker instead of per attempt.
  • Stale worker references: clearing them after delivery.

Only this source moved the phases: at 10 × 75, mark older went from 1.3 to 0.8 ms. Marked bytes barely changed (299 → 270 KB), so the cost is walking cards, not marking bytes. The cancellation source gave a small gain at 50 sessions only, and clearing stale references gave none.

Results

Paired rotated runs, runs overlapping other load discarded. Workstation GC client, server with Server GC. Measured on this change merged with master as of 2026-11-06. Values are medians, with ranges in brackets.

Traced, 3 runs per side (GC phases are averages per blocking collection):

Events, managed Baseline This PR
50 sessions × 15 subscriptions: events/s 1.57 M (1.52–1.67) 1.90 M (1.81–1.91)
delivered 95.8 % (90.2–96.4) 97.8 % (97.8–98.7)
pause p50 8.7 ms (8.5–8.9) 7.5 ms (7.4–7.8)
mark older + plan/relocate/compact 7.9 ms 6.6 ms
10 sessions × 75 subscriptions: pause p50 4.7 ms (4.7–4.8) 3.3 ms (3.3–3.4)
total pause in the 15 s window 7.5 s (7.4–7.7) 5.3 s (5.0–5.5)
mark older + plan/relocate/compact 4.1 ms 2.7 ms

Untraced, 3 runs per side (2 for the low-load row):

Events, managed Baseline This PR
50 × 15: delivered 92.8 % (92.7–93.8) 96.1 % (95.3–98.3)
10 × 75: delivered 99.8 % 99.7 %
10 × 15: delivered 99.9 % 99.8 %

Allocation per event is unchanged.

At 50 sessions the total pause stays about 12 s of 15 s. Pauses are shorter, but more events get through, so there are more collections. The rest of mark older there comes from pooled async state machine boxes of in-flight Publish requests.

Testing

  • New AvailabilityWindowTests cover the linear and hashed paths, replacing a view in both directions, and not keeping the caller's array.
  • New AvailableInRetransmissionQueueShouldReturnACopyOfTheLatestValuesAsync covers the property.
  • Locally on net10.0: the Subscription, SubscriptionEngine and SessionTransferAcknowledgement subset of Opc.Ua.Client.Tests (959 tests) and all of Opc.Ua.Subscriptions.Tests (670 passed, 4 skipped).
  • Locally on net48 (Release): AvailabilityWindowTests and MessageProcessorTests (91 tests).

🤖 Generated with Claude Code

Every Publish response replaced the array referenced by the long-lived
AvailabilityWindow and MessageProcessor.AvailableInRetransmissionQueue.
Each such write from an old object to a young array is a dirty card that
the next gen0 collections walk, in the mark and again in the relocate
phase. Both now copy into storage they keep; the property returns a copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@marcschier
marcschier merged commit 677ef5c into romanett/client-event-bytes Nov 8, 2026
21 checks passed
@marcschier
marcschier deleted the romanett/client-gc-availability-cards branch November 8, 2026 05:37
marcschier pushed a commit that referenced this pull request Nov 14, 2026
…nly bytes after dispatch (#5003) (#5073)

# Description

Fixes the classic-client part of #5003: under a high event load, a
classic `Session` / `Subscription` client with Workstation GC falls
behind the server, because every collection promotes the decoded
notifications that the client still holds.

### Cause

Deferred notification decoding (#5017, merged through #5005) fixed this
for the V2 engine. A Publish body stays raw bytes until dispatch, and
the engine releases it afterwards. The classic engine did not use it. A
classic `Subscription` also keeps every message reachable after its
dispatch: in its message cache (`MaxMessageCount`, default 10, behind
`Notifications` / `LastNotification`), and through the `Message`
back-reference on each notification in the monitored item caches. So the
decoded notifications of about the last second survive every gen0
collection.

To find out what matters, retention sources were toggled one at a time
in the harness (classic, Workstation GC client, 50 sessions × 15
subscriptions):

| Toggle | Survived per gen0 |
|---|---:|
| none (master) | 7.7 MB |
| `MaxMessageCount = 0`, monitored item cache off | 7.7 MB |
| deferred decoding only | 7.7 MB |
| deferred decoding, no message cache, item cache off, no release | 5–6
MB |
| deferred decoding, no message cache, bodies released after dispatch |
0.9–1.1 MB |

Only dropping the decoded value after dispatch helps. A body that waited
in the queue is already promoted, and its decoded value then stays alive
with it.

### Changes

- **`Session.DeferNotificationDecoding` (new public property, default
`true`).** Deferred decoding is now on for the classic engine too. It
was an internal property that only `ManagedSession` set for the V2
engine. `ManagedSessionOptions.DeferNotificationDecoding` now applies to
both engines.
- **Classic `Subscription` rewinds each deferred body after dispatch.**
New `DeferredExtensionObjectBody.Rewind` /
`ExtensionObject.RewindDeferredBody`: the decoded value is dropped and
the bytes are kept. A later read of a cached message decodes it again,
as a new instance with the same content. `Notifications` and
`LastNotification` keep working.
- **Messages that leave the cache return their pooled buffers.** This
happens at the end of the dispatch round, so a message is never released
before it is dispatched. A message is kept while it is still the
`MonitoredItem.LastMessage` of an item. Otherwise, it applies only while
the application cannot hold the message: never after it read
`Notifications`, `LastNotification` or `MonitoredItem.LastMessage` for
that subscription, and never after a message was saved while the session
had a `Session.Notification` handler (the mark stays with the
subscription when it moves to another session). These marks are sticky,
so there is no timing window. Without that release the cache holds new,
young buffers. With an exact-size copy instead, the measurement stayed
at 2.3 MB survived per gen0.
- **A cached body decoded again gets the dispatch state back.** `Rewind`
takes a callback that runs on each later decode; the classic
`Subscription` uses it to set `PublishTime`, `SequenceNumber` and
`MoreNotifications` of the notification list, and `Message` and
`DiagnosticInfo` of each notification, as the dispatch did.
- `DeferredExtensionObjectBody.Value` takes the body lock unless a
decoded value is present, so a read never races a rewind. The pooled
buffer now goes back to the pool on `Release`, not right after decoding;
the V2 engine releases right after dispatch, as before.
- Docs: `docs/Sessions.md` ("Deferred notification decoding", now for
both engines) and a client entry in `docs/ProductionChecklist.md`
(Server GC or a larger gen0 above about 1 M notifications/s, small
`MaxMessageCount`).

### Behaviour changes

- Classic sessions defer notification decoding by default. As already
documented for the V2 engine, a notification body that cannot be decoded
is logged and not delivered, instead of failing the whole Publish
response. Set `Session.DeferNotificationDecoding = false` to decode on
arrival.
- Reading a cached message (`Notifications`, `LastNotification`,
`MonitoredItem.LastMessage`) after its dispatch returns new instances of
its `DataChangeNotification` / `EventNotificationList`, with the same
content and the values the dispatch set. Code that compares them by
reference with the instances its callbacks got, or that looks up an
acknowledgement handle for them, sees different objects.
- A message reached only through `MonitoredItemNotification.Message` or
`EventFieldList.Message` has no notification data after it left the
cache, unless one of the hand-out conditions above holds.
- `ManagedSessionOptions.DeferNotificationDecoding` /
`WithoutDeferredNotificationDecoding()` now also apply to a
`ManagedSession` with the classic engine.

### Results

`perf/ServerLoadHarness`, the issue's command: `events`, 50 sessions ×
15 subscriptions, encrypted, 100 ms publishing interval, unthrottled
server with Server GC, client with Workstation GC, 15 s measured after
10 s warm-up. Same binary for all rows. The baseline sets
`DeferNotificationDecoding = false`, which is master's classic
behaviour, because the rewind does nothing without deferred bodies. 3
rounds each, run interleaved. The host had other work at times, and the
server's event generation rate varied between runs (0.16–2.4 M events/s
delivered), so delivery is noisy. Survived per gen0 is the steady
signal.

| Classic client | Delivered | Survived per gen0 | Client gen2 at end |
Client bytes per event |
|---|---:|---:|---:|---:|
| without deferral (master) | 41–43 % | 7.7 MB | 1.1–4.8 GB | 374–383 |
| without deferral, `MaxMessageCount = 1` | 45–55 % | 7.7 MB | 0.5–0.6
GB | 375–384 |
| **this PR, defaults** | **85–89 %** | **1.1–1.3 MB** | **~290 MB** |
382–392 |
| **this PR, `MaxMessageCount = 1`** | **86–99 %** | **1.0–1.2 MB** |
**71–78 MB** | 381–395 |
| managed client (reference) | 99.6–99.9 % | 0.6–0.7 MB | 66–70 MB |
415–416 |

### Tests

- `DeferredExtensionObjectBodyTests`: rewind decodes again as a new,
equal instance; rewind before the first read; release after rewind;
rewind after release; other bodies untouched; a malformed body is
available as bytes again; readers concurrent with rewinds always see a
value.
-
`SubscriptionUnitTests.CachedMessageKeepsDeferredBodyAsBytesAfterDispatchAsync`:
fails on master, where the cached message returns the dispatched
instance.
-
`SubscriptionUnitTests.EvictedMessageReleasesDeferredBodyUnlessHandedOutAsync`:
with no hand-out the body is released; with a `Session.Notification`
handler or a `LastNotification` read it stays readable.
-
`AcknowledgementProviderIntegrationTests.DeferredNotificationDecodingFollowsTheOptionAsync`:
the classic engine now follows the option (the test asserted "off"
before).
- Review follow-ups:
`EvictedMessageStaysReadableAsLastMessageOfAQuietItemAsync`,
`MessagesHandedOutBeforeASessionChangeStayReadableAsync` (each fails
without its fix), `RewindCallbackRestoresStateOnEachLaterDecode`, and
dispatch state checks in
`CachedMessageKeepsDeferredBodyAsBytesAfterDispatchAsync`. CI found
`Opc.Ua.Subscriptions.Classic.Tests.TransferSubscriptionAsync(*,*,True)`
reading sequence number 0 from a cached message; this is fixed by the
restore callback.
- Local runs (net10.0): `Opc.Ua.Client.Tests` 3845 passed / 0 failed / 2
skipped (before the restore callback), `SubscriptionUnitTests` 89 passed
after it; `Opc.Ua.Subscriptions.Classic.Tests` 59 passed;
`Opc.Ua.Subscriptions.Tests` 673 passed / 0 failed / 4 skipped (first
commit); `DeferredExtensionObjectBodyTests` 33 passed.
`Opc.Ua.Client.Tests` (with `Opc.Ua.Client` and `Opc.Ua.Types`) builds
for net48. net48 tests were not run, and the full UA.slnx suite was not
run.
- CI: the remaining build failures are CA2027 from the .NET 11 SDK in
code already on master, fixed by #5072.

## Related Issues

- Part of #5003: the classic client and the client GC guidance. The
managed client was addressed by #5005 (#5017, #5023, #5024). Still open
from the issue: the harness `events`/`sub` scenario lists do not set the
client GC explicitly.

## 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.
- [ ] If this PR changes C# source files, I ran **all** tests locally
using the **UA.slnx** solution against at least .NET **Framework** and
.NET **10**, and all passed. PRs changing only non-C# files do not
require these .NET test runs.
- [ ] 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](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.

2 participants