Repository navigation
Client: keep available sequence numbers without a new array per response - #5024
Merged
marcschier merged 1 commit intoNov 8, 2026
Merged
marcschier merged 1 commit into
marcschier merged 1 commit into
Conversation
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
approved these changes
Nov 8, 2026
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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)andplan+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
SubscriptionManageravailability window andMessageProcessor.AvailableInRetransmissionQueue. Each of these writes dirties a card that the next collections walk.Change
AvailabilityWindowcopies the numbers into a fixed 16-entry array, or into its existingHashSetabove 16 entries, instead of keeping the response's array.AvailableInRetransmissionQueueis 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:
Only this source moved the phases: at 10 × 75,
mark olderwent 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):
Untraced, 3 runs per side (2 for the low-load row):
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 olderthere comes from pooled async state machine boxes of in-flight Publish requests.Testing
AvailabilityWindowTestscover the linear and hashed paths, replacing a view in both directions, and not keeping the caller's array.AvailableInRetransmissionQueueShouldReturnACopyOfTheLatestValuesAsynccovers the property.Opc.Ua.Client.Tests(959 tests) and all ofOpc.Ua.Subscriptions.Tests(670 passed, 4 skipped).AvailabilityWindowTestsandMessageProcessorTests(91 tests).🤖 Generated with Claude Code