Skip to content

Client: address review findings on deferred notification decoding - #5023

Merged
marcschier merged 1 commit into
romanett/client-event-bytesfrom
romanett/deferred-decode-copilot-fixes
Nov 7, 2026
Merged

marcschier merged 1 commit into
romanett/client-event-bytesfrom
romanett/deferred-decode-copilot-fixes

Conversation

@romanett

@romanett romanett commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Follow-up to #5017, addressing its Copilot review. Stacked on #5005, because that is where #5017 landed; it is not on master yet.

All five findings were real. Severity below is my read after tracing the code, not Copilot's label.

Finding Assessment Fix
Nesting limit bypass Real, but off by one level: an empty body at the limit + 1 was accepted. Nested reads were still checked, so recursion stayed bounded. Same check as the eager path, before renting.
Malformed body discards the valid ones Real, the most serious one. With a whole-message handler, Create threw, so the whole message was lost and still acknowledged, including its status changes. The projection skips a deferred body that has no value. Unknown payload types still throw.
Log flood Real, needs a misbehaving server. One log per response, shared across its bodies, as the eager decoder does.
Policy lost on a replaced transport Real, performance only: decoding silently went back to eager. The session holds the policy and reapplies it before each Publish.
Shared context lets sessions interfere Real on a shared channel manager (the DI singleton), but not a correctness bug: deferred bodies decode on first read. Partly fixed, see below.

Decision for the reviewer: shared transports

Sessions no longer overwrite each other, so the result does not depend on connection order: a session only ever turns deferral on. But it is still per transport. A classic or opted-out session that shares a transport with a deferring one gets deferred bodies. It still sees every notification; the difference is that a malformed body is skipped rather than failing the response. This is documented in docs/Sessions.md.

Fully isolating sessions needs one of two larger changes, neither done here:

  • Per-request: carry the choice from the Publish request to the decoder through the channel layers, and around the generated PublishAsync.
  • Per-channel key: put the policy in EndpointConfiguration so that it separates channels. This stops V2 and classic sessions sharing a transport, and every endpoint path has to keep the flag.

If you want strict isolation, say which, and I will do it here or as a follow-up.

Other notes

  • A message whose bodies are all malformed reaches a whole-message handler with no payloads.
  • The failed decode attempts themselves are not bounded, only their logging. Stopping after a budget would drop valid bodies behind the bad ones.
  • Session.DeferNotificationBodies replaces the direct write to the message context in ManagedSession. The public ServiceMessageContext.DeferNotificationBodies is unchanged.
  • Also adds the missing final newline in DeferredExtensionObjectBody.cs.

Testing

  • New tests for the nesting limit (deferred and eager), log-once, the projection, whole-message delivery, a replaced transport, and not clearing a shared transport. The replaced-transport test swaps the context behind a mock channel; this was not tested against a real reconnect, and no test connects two real sessions to one channel manager.
  • With each of the four core fixes temporarily undone, its test failed. The test that a non-deferring session leaves a shared transport alone was not part of this check.
  • net10.0: Opc.Ua.Types.Tests 13990 passed; Opc.Ua.Client.Tests 3656 passed, 2 skipped; AcknowledgementProviderIntegrationTests 11 passed. The rest of Opc.Ua.Subscriptions.Tests was not run.
  • net48: the new and related tests only (19 and 41 passed).
  • No load benchmark: the only hot-path addition is one flag check per Publish.

🤖 Generated with Claude Code

- Enforce MaxEncodingNestingLevels on a deferred body before renting.
- Skip a malformed deferred body in the whole-message projection, so the
  valid payloads next to it still reach the handler.
- Log one malformed body per response, as the eager decoder does.
- Keep the policy on the session: reapply it before each Publish, because
  a replaced transport starts with a new message context, and never clear
  it, so sessions sharing a transport no longer overwrite each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@marcschier
marcschier merged commit 0068b03 into romanett/client-event-bytes Nov 7, 2026
21 checks passed
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