You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
N13 of the NodeManager lifetime redesign: namespace default permissions (DefaultAccessRestrictions, DefaultRolePermissions, DefaultUserRolePermissions) are now cheap to read, and a changed default still applies to the very next check.
Two problems, both measured in #5168 (perf/results/lifecycle-baseline-2026-11-24.md):
Quadratic per-request cache.OperationContext.SetDefaultPermissions copied the array and appended one element per namespace, and TryGetDefaultPermissions scanned it linearly. A Read over N namespaces allocated arrays of 1..N and did O(N²) lookups. In f5-m64-r64, 84 % of server allocation was NamespaceDefaultPermissions[].
No cache for long-lived contexts. Monitored-item and subscriber contexts remembered nothing, so every check re-read the metadata variable via BaseVariableState.ReadValueAttribute under its node lock. Under read load that was 99 % of all lock contention.
Change
NamespaceDefaultPermissionCache (new), server-wide, owned by NamespaceMetadataRegistry. It caches the decoded defaults of each namespace whose defaults are static: stored values, no read callbacks, and readable in both access levels. A static decode does not depend on the caller, so every context can share it. Entries are indexed by namespace index in an array that only grows. On each hit the cache checks, without taking a lock:
NamespaceDefaultPermissionReader.Generation is unchanged. The registry already moves it on every reported value change of a default property (ClearChangeMasks → StateChanged), on any add, replace or remove of a default property, and on any link, relink or removal of a metadata node. That covers dynamic namespaces and a manager's namespace being removed or reloaded through the lifecycle.
No default property has a pending, unreported Value change mask. A value assigned in process without ClearChangeMasks raises no notification. That namespace is read live until the change is reported, so the change still applies to the next check, as it did before.
The metadata node still exposes the same property instances, and each is still static. A read callback assigned later, or read access revoked later, takes effect at once.
A namespace without metadata is not cached here. The registry's own miss cache answers it, because that cache also sees unreported Server/Namespaces changes.
Detach clears the cache.
NamespaceDefaultPermissionReader.Read/ReadAsync look in the request cache first, then the server cache. They decode only on a miss and fill both caches (the server cache only when the defaults are static).
Per-request cache (OperationContext). It now holds only caller-dependent (callback) defaults. It is indexed by namespace index: a slot array sized to the highest index seen (up to 64), then a ConcurrentDictionary. Each slot is replaced whole, so concurrent validation within one request is safe. It is O(1) per lookup and allocates no more than linearly.
MasterNodeManager.NodeManagement.cs and the verdict caches are untouched; N6 is in a parallel PR.
A reported change applies to the next check of a monitored-item context (sync and async).
An unreported change applies at once and bypasses the cache until it is reported.
Callback defaults are read on every check and never cached.
A callback assigned later retires the entry.
Removing a namespace's metadata leaves no stale defaults.
Clear and growth beyond the initial size.
OperationContextDefaultPermissionsCacheTests: 300 namespaces across the slot/dictionary boundary, a generation change, 64k concurrent get/set over 160 namespaces with no cross-namespace result, and disabling drops entries.
Opc.Ua.Server.Tests net10.0: 12316 passed, 10 failed. All 10 are local-environment failures:
8 need symlink privilege.
FileSystemAccessRegressionTests failed with a teardown file lock and SimulationRegistryTests.RegisteredLoopFiresAfterStart on a 200 ms timing assertion under load. Both pass when rerun alone.
#5168 harness, Release net10.0, Server GC, binaries copied to short paths, master fa144238f vs this branch, alternating order, 3 rounds each, runs with more than 3 foreign cores discarded. Per Read = one 64-node Read request. Means of 3 rounds:
Line
Side
Reads/s
Alloc/Read
CPU/Read
Server contention (15 s)
f5-m64-r1
master
44,936
15.5 KB
160 µs
517
f5-m64-r1
branch
45,078
15.5 KB
159 µs
473
f5-m64-r64
master
19,412
162.5 KB
430 µs
4
f5-m64-r64
branch
21,762 (+12 %)
35.4 KB (−78 %)
353 µs (−18 %)
6
f5-m64-r64 now allocates 2.3× f5-m64-r1, down from 10.5×.
f5-m64-r1 is unchanged (+90 B per Read, within noise). A first cut with a fixed 64-slot request array cost +540 B per Read; the array now grows to the highest index seen.
After the review fix in ce888ada5 (cached role entries are copied on every hit), a new 3-round A/B on a less loaded machine gave:
f5-m64-r1: 15.4 → 15.2 KB per Read, 133 µs on both sides.
lc-ctl (10 sessions × 5 subs × 100 nodes, 4 readers, 8 managers), means of 3 rounds:
Side
Notif/s
Reads/s
Server CPU (15 s)
Server alloc (15 s)
Server contention (15 s)
master
48,875
33,700
62.7 s
4,536 MB
3,799
branch
50,139
33,657
61.8 s
4,035 MB (−11 %)
18 (−99.5 %)
On master, 99 % of the lc-ctl contention came from BaseVariableState.ReadValueAttribute called by NamespaceDefaultPermissionReader from monitored-item contexts. That is gone: what remains is ~18 events per 15 s.
Reuse for N14
The per-node DefaultPermissionsChanged subscription can be replaced by a version stamp. MonitoredNode2 subscribes once per monitored node, which is O(monitored nodes) per add/remove. Instead, it can record NamespaceDefaultPermissionReader.Generation when it builds its permission verdicts, and compare it on use, the way the cache entries do. That makes add/remove O(1), and the subscribe/unsubscribe goes away. The global generation alone would make every namespace's verdicts rebuild on any change, and today a cache entry's identity also changes on every global bump, so it is no per-namespace stamp yet. For that, NamespaceDefaultPermissionCache can keep a long counter per namespace slot, incremented only when that namespace's decoded defaults differ from the entry they replace, or when its own entry is retired by IsCurrent. Verdicts then hold (namespaceIndex, stamp), and a change to one namespace invalidates only its verdicts. A verdict must also treat "no current cache entry" (callback defaults, or a pending unreported change) as uncacheable, as the entries do, or unreported changes would be missed.
…uest cache
The namespace defaults (DefaultAccessRestrictions, DefaultRolePermissions,
DefaultUserRolePermissions) were remembered per request in a copy-on-write
array that grew by one per namespace, with a linear lookup, so a request over
N namespaces cost O(N^2). Long-lived monitored item and subscriber contexts
remembered nothing and re-read the metadata variable under its node lock on
every check.
Static defaults (stored values, no read callbacks, readable) are now cached
server-wide per namespace index in NamespaceDefaultPermissionCache. An entry
is used only while NamespaceDefaultPermissionReader.Generation is unchanged,
no default property has a pending unreported value change, and the metadata
node still exposes the same static properties, all checked without a lock,
so a changed default still applies to the very next check. The per-request
cache, now only for caller-dependent defaults, is indexed by namespace index
(64 slots, then a concurrent dictionary).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
❌ Patch coverage is 94.91525% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.85%. Comparing base (fa14423) to head (13c77f5). ⚠️ Report is 13 commits behind head on master.
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.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Two critical cache-isolation flaws let returned metadata mutate later authorization and allow self-removing callbacks to share caller-specific permissions server-wide.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Critical cache invalidation gaps can preserve revoked permissions after value-equal role-array replacement and return stale access restrictions during change notifications.
No open issues 🎉
2 previously missed issues
In code that hasn't changed since last review
Equal role-array replacement leaves stale cached grants
After the cache is populated, assigning a new, value-equal role array and then revoking a permission in that replacement leaves this check examining the old objects, so fresh requests still receive the old grants. The equal assignment sets no Value change mask, and m_stored is a separate array captured by TryGetStructure, not the property's current storage. Validate current storage or track its replacement independently of value equality, and test this sequence for both DefaultRolePermissions and DefaultUserRolePermissions.
Access-restriction changes expose stale cache before generation updates
ClearChangeMasks clears the Value bit before invoking OnStateChanged, while the registry advances Generation only in the later StateChanged event. After changing DefaultAccessRestrictions from None to EncryptionRequired, a permission check inside OnStateChanged or concurrently with that handler can therefore return the cached None. Track a value revision that survives mask clearing, or validate current restrictions and status before accepting the entry; add a regression that reads from OnStateChanged.
Addressed the two issues from the latest Copilot review summary in be541ba:
Equal role-array replacement / report window:BaseVariableState has a new internal ValueVersion, moved by every value or status assignment, including value-equal ones and ones not yet reported. The cache captures the three default properties' versions before decoding, and an entry is used only while they still match. So an equal replacement (later revoked in place) and a check made inside OnStateChanged before the registry moves the generation both read the new value.
Tests:EqualReplacementThenInPlaceChangeAppliesAsync (DefaultRolePermissions and DefaultUserRolePermissions) and ChangeAppliesWhileItIsReportedAsync. All three fail without the version check.
…lt property
BaseVariableState gets an internal ValueVersion moved by every value or
status assignment, including value-equal ones and ones not yet reported.
The cache captures it before decoding and checks it on every hit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because permission caching can bypass caller-specific access checks or retain stale restrictions after property reinitialization.
Follow-up to the latest Copilot summary (stale restrictions after property re-initialization): BaseVariableState.Initialize(context, source), reached through the public NodeState.Create(context, source), replaced the value of a live property without a change mask or a version move. It now moves ValueVersion too in d652d43. Regression: ReinitializedPropertyAppliesToNextCheckAsync, which fails without the change. Caller-specific defaults stay uncached: an entry requires no read callbacks and no OnReadUserAccessLevel before and after the decode, and read access in both access levels.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because callback-free custom read overrides can cause caller-specific access restrictions to be cached server-wide, potentially bypassing another caller’s security requirements.
Follow-up to the latest Copilot summary (callback-free read overrides): in fc347b3 the server-wide cache stores a namespace's defaults only when each default property's type is defined by the stack (Opc.Ua.Types or the generated Opc.Ua.Core types). Those types read their stored value unless a callback is set, which IsStatic already rules out. A subclass from another assembly can override ReadValueAttribute/ReadAttribute and return a caller-specific value, so its defaults are read live on every check, as before this PR. This is a type check, not reflection, so it is trim-safe. Regression: OverriddenReadIsNotCachedAsync, which fails without the check.
…he stack
A subclass from another assembly can override the value read and return a
caller-specific value without a callback; its defaults are read live.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because concurrent reinitialization can preserve a successful cached result despite a Bad status, while shared-generation test interference can cause intermittent failures.
Follow-up to the latest Copilot summary, in 13c77f5:
Concurrent re-initialization:BaseVariableState.Initialize(context, source) copies the value and status without a lock. It now moves ValueVersion after the copy, not before. A decode that read the version before or during the copy no longer matches, so a result decoded from a half-copied state (Good value, Bad status) is never used.
Shared-generation tests:NamespaceDefaultPermissionCacheTests and OperationContextDefaultPermissionsCacheTests depend on the process-wide NamespaceDefaultPermissionReader.Generation. Other fixtures move it, for example when a server starts, so both fixtures are now [NonParallelizable].
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Authorization-sensitive lock-free caching and shared-variable writes need human follow-up because concurrent update/reload behavior on supported .NET runtimes could not be validated.
…he changed nodes (#5182)
## Problem (N6 of the NodeManager lifetime redesign, F4 of #4931)
`DispatchAdmittedAddNodesAsync` and `DeleteNodesAsync` called
`NodeState.InvalidateRolePermissionsCache()` before per-item
authorization and again in `finally`. That moved one server-wide version
and retired every cached sampled-read, data-change and event
authorization verdict on the server. It happened even for a request
whose items were all rejected, and on the ReferenceServer an anonymous
session's AddNodes succeeds. In #5168 (`n6-sub` vs `n6-sub-nm`, 20
AddNodes+DeleteNodes pairs/s next to a write-driven subscription load)
this raised allocation per notification from 171 B to 774 B and lock
contention from 11 to about 19,300 events per 15 s.
## Design: per-instance versioning
Every verdict cache already keys on the source **node instance**:
`ReferenceEquals(verdict.ReadNode, node)`,
`MonitoredItemPermissionContext.Node`, and the event cache's weak
`SourceNode`. Namespace defaults have their own versioning:
`NamespaceDefaultPermissionReader.Generation`, plus
`DefaultPermissionsChanged` raised by `NamespaceMetadataRegistry` when
default properties are added, replaced or removed. Role checks have no
inheritance through `HasComponent` or type definitions: a verdict
depends only on the checked node's own `RolePermissions`,
`UserRolePermissions` and `AccessRestrictions` and on its namespace
defaults.
So node management can change exactly one input of an existing verdict:
whether its instance is still the node that its NodeId resolves to. That
is now an instance-local version:
- `NodeState.PermissionVersion` (internal, stored in the lazily
allocated `NodeStateSecurityData`, so nodes that are never deleted pay
no memory) moves when the node is marked `Deleted`, via
`UpdateChangeMasks` or the `ChangeMasks` setter.
`AsyncCustomNodeManager.RemovePredefinedNodeAsync`,
`CustomNodeManager2`, WotCon and `NodeState.Delete` already mark every
removed node of the subtree.
- Every verdict key folds it in: `MonitoredReadInputs` (sampled and
data-change exact-source read verdicts),
`MonitoredReadAuthorization.ValidateAsync`'s recheck loop,
`MonitoredItemPermissionContext` and the data-change generation, the
event source cache (`CachedEventPermission.SourceVersion`, captured
before validation) and the sampling group's role verdict
(`PermissionVerdict.NodeVersion`).
- Each loop captures the version before validating and compares it
afterwards. A deletion during validation therefore retries, and a
verdict computed between removal and marking is retired by the mark. The
old "before mutation" bump is no longer needed.
I preferred this over NodeId-scoped invalidation because verdicts are
already per instance. A per-NodeId table would need a lifetime of its
own, and a per-namespace version would not help the measured case: the
monitored nodes and the added nodes share a namespace.
`MasterNodeManager` now moves the server-wide version only when a
node-management item can change verdicts that no instance version
covers:
| Case | Server-wide bump |
|---|---|
| Item rejected (validation, permission, unknown node, owner returned
Bad) | no |
| AddNodes success, ordinary node | no (new instance, no verdict cached
for it) |
| AddNodes success, `NamespaceMetadataType`, a
`Default*Permissions`/`DefaultAccessRestrictions` property, or parent
`Server/Namespaces` | yes |
| DeleteNodes success, `AsyncCustomNodeManager` / `CustomNodeManager2`
owner | no; the master also moves the deleted instance's own version |
| DeleteNodes success, deleted `BaseTypeState` (event verdicts key on
the type's NodeId) | yes |
| DeleteNodes success, namespace-metadata-related node | yes |
| DeleteNodes success, handle is not a `NodeState` or owner is a
third-party manager | yes (cannot know its removed instances) |
| Owner threw mid-item | yes |
Role-permission attribute setters still move the server-wide version
(unchanged; narrowing them is a possible follow-up).
## Tests
- `MasterNodeManagerNodeManagementTests`:
- Rejected AddNodes and rejected DeleteNodes keep the version.
- A successful ordinary AddNodes keeps the version.
- A namespace-metadata AddNodes moves it (type and property cases).
- A delete on an untracked owner moves it.
- A DeleteNodes through a real `AsyncCustomNodeManager` moves the
deleted node's and its child's instance version but not a sibling's, and
leaves the server-wide version alone.
- `MonitoredNode2Tests`: deleting the monitored node re-validates its
cached data-change permission; deleting an unrelated node does not.
- `SampledReadVerdictCacheTests`: `NodeDeleted` is a key that retires
the sampled verdict, and the deletion of an unrelated node keeps it.
- Existing role-permission-change, default-permission and channel tests
are unchanged and pass.
## Measurements
`ServerLoadHarness` from #5168 (`--scenario lifecycle-reload --sessions
10 --subs 5 --nodes 100 --pub 100 --write-interval 100 --readers 0
--lc-managers 1 --lc-interval 0`; `n6-sub-nm` adds `--addnodes 50`).
Release net10.0, Server GC, master `fa144238f` vs this branch,
alternating master/fix runs, 15 s each. All runs had 0 cores of foreign
load. Medians, with [min..max] in brackets.
**`n6-sub-nm`** (subscriptions + 50 AddNodes per pass, 4 rounds):
| | master | this PR |
|---|---|---|
| alloc / notification | 770 B [766..1072] | **176 B** [175..178] |
| server CPU / notification | 12.7 µs [11.4..15.6] | **7.8 µs**
[4.8..8.9] |
| lock contention | 19,319 [18,995..20,606] | **13** [9..22] |
| server alloc / 15 s | 549 MB | **125 MB** |
| server CPU | 0.59 cores | 0.39 cores |
| delivered | 99.3 % [71.1..100] | 99.7 % [99.3..100] |
| node-management calls good / bad | 301 / 0 | 301 / 0 |
With this PR, `n6-sub-nm` costs about the same as plain `n6-sub` (#5168
baseline: 171 B, contention 11). Node management no longer adds a
per-notification cost.
**`n6-sub`** (subscriptions only, 8 rounds):
| | master | this PR |
|---|---|---|
| alloc / notification | 153 B [151..168] | 153.5 B [152..180] |
| server CPU / notification | 5.5 µs [4.0..6.8] | 7.4 µs [4.7..8.5] |
| lock contention | 19 [4..30] | 13 [8..30] |
| server alloc / 15 s | 109 MB | 109 MB |
| delivered | 99.3 % [92.7..100.7] | 99.3 % [82.8..100] |
Allocation and contention on `n6-sub` are unchanged. CPU per
notification is noisy (4.0 to 8.5 µs across 16 runs), and the median on
this branch is 1.8 µs higher. The added work on this path does not
explain that difference: the harness nodes have no role permissions or
access restrictions, so `NodeState.m_securityData` is null and
`PermissionVersion` costs one null check. Every other addition is a
`long` compared next to fields that were already compared. The
difference most likely comes from run-to-run variance in sequential
runs, which is large on this machine. A paired A/B or an A/A control run
would settle it. The two 83 % delivery runs on this branch were noise:
the four later rounds delivered 99.3 to 100 %, and one master run
dropped to 92.7 %.
## Coordination with N13
The remaining cost of a verdict rebuild (re-reading namespace defaults
under the metadata variable's node lock, 99.9 % of the measured
contention) is N13, now merged as #5183 (`OperationContext.cs`,
`NamespaceDefaultPermissionReader.cs`, `MonitoredNode.cs` defaults
handling). This PR does not touch those parts. It only removes the
reason for rebuilding on node management. In `MonitoredNode.cs` it
changes only `CapturePermissionContext`, the generation sums, the event
source cache and `MonitoredItemPermissionContext`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Part of the NodeManager lifetime follow-ups (#4931), item N14.
## Problem
Every `MonitoredNode2` subscribed to the server-wide
`IConfigurationNodeManager.DefaultPermissionsChanged` event when its
first item was added, and unsubscribed when its last item was removed.
Every `SamplingGroup` did the same on startup and shutdown. Each `+=` /
`-=` rebuilds the multicast invocation list, an array as long as all the
subscribers. Adding or removing a monitored item therefore cost
O(monitored nodes on the server), and reloading a manager with many
monitored nodes was quadratic. The #5168 baseline (`f4-sampled-churn`:
20 managers × 500 variables, one reload per second) attributes half of
the reload allocation to that `object[]` in `MonitoredNode2.Remove`.
## Change
- New internal `DefaultPermissionsVersion`: one subscription per
configuration node manager, which counts its notifications. It is held
in a `ConditionalWeakTable` keyed on the manager and subscribes exactly
once. Each counter starts in its own 2^32 range, so a verdict stamped
against a replaced configuration manager never matches.
- `MonitoredNode2` folds the counter into the generation that stamps its
cached data-change verdicts, event verdicts and event-restriction
verdicts (`PermissionGeneration`). `Add`, `Remove` and `Dispose` no
longer touch the event.
- `SamplingGroup.PermissionEpoch` folds in the same counter instead of a
subscription per group. A group also no longer misses a change that
arrives between `Shutdown` and the next `Startup`.
Semantics are unchanged: every notification still invalidates every
cached verdict before it is next used. The counter is captured before
validation and compared again before the verdict is stored, the same way
`m_permissionGeneration` already worked. A change that never raises the
event is handled as before: the registry and namespace-default cache
stamps (`NamespaceDefaultPermissionReader.Generation`, static-defaults
checks) are untouched.
I chose this over a per-namespace counter in the #5183 cache. The event
fires for exactly the changes it covers today, including defaults behind
read callbacks, namespaces without cache entries and custom
`IConfigurationNodeManager` implementations. Narrowing invalidation to a
single namespace would be a separate optimisation, and today's event
invalidates every namespace too.
## Measurements
**Micro-measure** (new test
`AddAndRemoveItemAllocationIsIndependentOfMonitoredNodeCount`, net10.0):
bytes allocated per add+remove of one item on one node.
| | 10 monitored nodes | 5,010 monitored nodes |
|---|---|---|
| master | 3,681 B | 134,434 B |
| this PR | 1,074 B | 1,074 B |
The test fails on master: 130,753 B more at 5,010 nodes.
**`f4-sampled-churn` A/B** (`lifecycle-reload --load 0 --readers 0
--lc-managers 20 --lc-vars 500 --lc-sampling 100 --lc-interval 1000
--lc-remove-every 0 --duration 15 --warmup 8`; the control line is the
same command with `--lc-interval 0`). Setup: master `567363fad` against
this branch, Release net10.0, Server GC, bins at `C:\un14m` and
`C:\un14b`, 4 rounds with the first side alternating, foreign load 0
cores in every run, 16 reloads per run with 0 failures on both sides.
Each cell is the median [min..max].
| | master | this PR |
|---|---|---|
| Server alloc / 15 s, churn | 872.6 MB [870.0..875.5] | 433.2 MB
[431.6..435.7] |
| Server alloc / 15 s, control | 55.2 MB [52.8..57.1] | 54.2 MB
[53.7..56.3] |
| **Alloc per reload, net** | **51.1 MB** | **23.7 MB (−54 %)** |
| Server CPU / 15 s, churn | 2,773 ms [2,188..2,984] | 1,742 ms
[1,547..2,094] |
| Server CPU / 15 s, control | 570 ms [453..625] | 547 ms [391..688] |
| **CPU per reload, net** | **~138 ms** | **~75 ms (−46 %)** |
| Apply p50 / p99 | 88 / 152 ms | 31 / 120 ms |
The net figures subtract the control median and divide by 16 reloads.
The #5168 baseline recorded about 54 MB per reload on master.
## Tests
- `MonitoredNode2Tests`: the dispose test now asserts that a node never
subscribes. A new test checks that three nodes share one subscription,
that cached verdicts are reused, and that one notification re-validates
every node.
`InFlightDataPermissionCannotReviveInvalidatedGrantAsync(defaultsChanged:
true)` still covers the in-flight race.
- `Opc.Ua.Server.Tests`, net10.0, full run: 12,539 passed, 9 failed.
Eight failures are the symlink tests, which need a privilege this
machine lacks.
`PreparedBatchImmediateCutoffPreservesCapturedNativeReadAsync(True)`
failed under full load and passed 3 times out of 3 when run alone.
- net48, subset (MonitoredNode / SamplingGroup / Permission /
MonitoredItem / Subscription / NamespaceMetadata /
ConfigurationNodeManager / Authorization): 2,602 passed, 0 failed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…NodeManager lifecycle qualification (#5214)
**This PR clears every `dotnet format` finding in Opc.Ua.Types,
Opc.Ua.Server, Opc.Ua.WotCon.Server, Opc.Ua.Server.Tests and
Opc.Ua.WotCon.Tests.** After it, `dotnet format <project>
--verify-no-changes` and `dotnet format analyzers <project>
--verify-no-changes` exit 0 for all five projects. It also records the
release qualification gates for the NodeManager lifecycle redesign
(tracking issue #4931).
### dotnet format cleanup
- **121 findings fixed in 49 files.**
- Whitespace: 78.
- Import order: 11.
- RCS0009 blank lines before doc comments: 28.
- RCS1139/RCS1142 doc tags: 3.
- Final newline: 1.
- **Formatting only, no code change.** The changes are whitespace,
`using` order, blank lines and doc comments. Where the fixer generated
empty `<summary>` or `<typeparam>` tags, I filled them in by hand.
- **Builds stay clean.** Release builds of Opc.Ua.Server.Tests and
Opc.Ua.WotCon.Tests (net10.0, including src) show 0 warnings and 0
errors.
- **Overlap with #5212:** one file,
`WotAtomicPublicationNativeTests.RetainedInputs.cs`, is also changed
there. The two PRs change different lines (373–383 here, 191 there), so
they merge cleanly.
- **The first run also reported 42 CA1001, CA1859 and CA2012 findings,
but they weren't real.** They came from a restore that the net48 test
builds had left behind:
- The messages name `ILogger` without its namespace.
- They ask for concrete return types on interface implementations such
as `ILogger.CreateLogger` and
`IXRegistryProjectionStrategy.CreateResourceFile`.
After a clean `dotnet restore UA.slnx`, the analyzer pass reports none,
so no source changed for them.
- **Why they had built up:** no CI job runs `dotnet format`, so findings
accumulate unnoticed. Adding a `--verify-no-changes` step to CI would
keep these projects clean.
### Release qualification (NodeManager lifecycle redesign)
The gates cover #4982, #5011 (`d8e5e29cd`) and the follow-ups #5168,
#5169, #5182, #5183 and #5206, tested on master `567363fad`. **Every
gate passed. The runs found no product failure and no regression.** Full
results, commands and per-file tables:
[`perf/results/qualification-2026-11-30.md`](https://github.com/OPCFoundation/UA-.NETStandard/blob/romanett/qualification-gates-n2/perf/results/qualification-2026-11-30.md).
| Gate | Result |
|---|---|
| Stress Contract + Integration (net10.0) | 45/45 passed (39 Contract +
6 Integration, the #5011 selection) |
| Stress ChaosTCP, seed 5011 | 6/6 passed |
| Stress subscription conformance, without LongRunning (extra) | 154/154
passed |
| Release analyzer builds: Types, Server, WotCon.Server (all TFMs);
Server.Tests and WotCon.Tests (net10.0, net48) | 0 warnings, 0 errors |
| `dotnet format` on the same 5 projects | All findings fixed (see
above). 0 were in `NodeManager/Lifecycle/` or
`NodeManagerGeneration.cs`, and 4 came from #4982/#5011. |
| Scoped lifecycle coverage (not the overall matched comparison),
`233b3930e` → master (Server.Tests NodeManager namespace, net10.0) |
Lines 87.18 % → 89.67 %, branches 78.86 % → 81.92 %. Tests 2,041 →
2,670, all passing. |
- **No net48 stress run:** the stress project has no net48 target. With
`CustomTestTarget=net48` it becomes a placeholder with no tests.
- **Lifecycle not stressed:** the stress categories don't add, reload or
remove a NodeManager under traffic. The 2,670 NodeManager-namespace
tests from the coverage gate cover the lifecycle itself.
- **One untested path:** no test reaches `LifecycleWriter`'s "failed
after a durable decision" refusal (lines 598–602). It is the only
behaviour path among the coverage drops.
### Proposed text for #4931 ("Qualification and performance")
Sub-items for the open item "Freeze and qualify the follow-up source".
The item itself stays unchecked: it asks for an overall matched CI
coverage comparison, and this PR only has the scoped lifecycle
comparison. I haven't edited the issue.
```markdown
- [ ] Freeze and qualify the follow-up source on master `567363fad`, which includes #5168, #5169, #5182, #5183 and #5206 ([results](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/perf/results/qualification-2026-11-30.md), PR #5214). Still open: the overall matched CI coverage comparison, and the final net48/net10 managed and non-Windows NativeAOT verdicts on the final revision.
- Stress, net10.0. Contract + Integration: 45/45 (39 Contract + 6 Integration, the #5011 selection). ChaosTCP seed 5011: 6/6. Subscription conformance stress without LongRunning: 154/154. The stress project has no net48 target.
- Analyzers: Release builds of Opc.Ua.Types, Opc.Ua.Server and Opc.Ua.WotCon.Server (all TFMs) and Server.Tests/WotCon.Tests (net10.0, net48): 0 warnings.
- `dotnet format`: all 121 style findings in those five projects are fixed. 0 were in `NodeManager/Lifecycle/` or `NodeManagerGeneration.cs`, and 4 came from #4982/#5011. `dotnet format --verify-no-changes` and `dotnet format analyzers --verify-no-changes` now pass on all five. The first run also showed 42 CA1001/CA1859/CA2012 findings, but they came from a stale net48 restore and are gone after a clean restore.
- Scoped lifecycle coverage only (not the overall matched comparison), `233b3930e` → master (Opc.Ua.Server.Tests NodeManager namespace, net10.0): lines 87.18 % → 89.67 %, branches 78.86 % → 81.92 %. Lifecycle tests 2,041 → 2,670, all passing. Per-file drops are in guard, compatibility and exception boilerplate. The largest are `IDynamicNodeManagerBatchHost` (branches −14.7) and `INodeManagerReadinessNotification` (branches −16.7).
- Not run: overall matched CI coverage, Soak, LongRunning stress, net11.0 stress.
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…replacements, old members obsolete (#5213)
N8 from the NodeManager lifetime work (tracking issue #4931, F12
identity and ambient state). This PR removes every `AsyncLocal` slot
that only existed because a released contract could not carry its state.
11 slots are gone. Each affected contract gained a replacement that
carries the state explicitly, and the old member is `[Obsolete]`. The
obsolete members keep working, but they lose the guarantee the slot used
to provide. The 10 slots that remain are documented with their reason.
## Removed slots
| Removed slot | Explicit replacement | Obsolete member | What the
obsolete member loses |
|---|---|---|---|
| HistoryRead request, manager callback and resumed read
(`SessionContinuationPoints`: 3 slots) | The dispatcher binds a
`HistoryFlow` to the `OperationContext` it passes to `HistoryReadAsync`.
New extensions `OperationContext.SaveHistoryContinuationPoint[Async]` /
`RestoreHistoryContinuationPoint[Async]`. |
`ISessionContinuationPoints.SaveHistory[Async]`, `RestoreHistory[Async]`
| A save is not pinned or reserved and can be evicted before the
response; its token binds to the returning callback only once (so legacy
managers still page). A restore reserves no Part 4 §7.9 slot and returns
null for the point of a resumed read. |
| `AddPredefinedNodeAsync` registration scope, AddNodes NodeId
reservation, driving address-space operation (`AsyncCustomNodeManager`
×2, `PredefinedNodesAddressSpace`) |
`AddPredefinedNodeAsync(ISystemContext, NodeState,
PredefinedNodeRegistration, CancellationToken)`;
`registration.ForChild()` for children |
`AddPredefinedNodeAsync(ISystemContext, NodeState, CancellationToken)` |
Overrides of it are still called for every node, but every node is
announced to the local address space (a root driven by the address space
is announced twice), and an AddNodes subtree loses its NodeId
reservation during indexing (the up-front reservations still apply). |
| All-events root change
(`AsyncCustomNodeManager.m_allEventsRootChange`) |
`SubscribeToEventsAsync` overload with `AllEventsRootChange?` | the old
protected `SubscribeToEventsAsync` hook | A release through the old hook
detaches the root directly instead of keeping it for another owner. |
| All-events dispatch binding (`GenerationReconciler.s_eventDispatch`) |
Optional interface `IAllEventsSubscriptionAsyncNodeManager` with
`AllEventsBinding` (no default interface members on
net48/netstandard2.0) | `IAsyncNodeManager.SubscribeToAllEventsAsync`,
the 5-parameter `AsyncCustomNodeManager.SubscribeToAllEventsAsync` | A
manager or facade with only the old member puts every change of a
monitored item under one owner; when two generations share one physical
subscription, releasing one can drop links the other still needs. |
| Legacy virtual lookup context
(`NodeManagerServiceDispatcher.m_legacyLookupContext`) |
`MasterNodeManager.GetManagerHandleAsync(OperationContext?, NodeId,
CancellationToken)`; the dispatcher passes the operation's context |
overriding `GetManagerHandleAsync(NodeId, CancellationToken)` (callers
keep using `IMasterNodeManager.GetManagerHandleAsync`) | An override of
the old overload is still called, but its base call resolves on live
routing without the request's readiness, so a manager whose
initialization is still pending is not found. Dispatch still confines a
managed owner to the pinned image. |
| Session-close callback permit
(`MasterNodeManager.m_lifecycleCallbackPermit` and its holder
`LegacyNodeManagerCallbackScope`) | `SessionClosingAsync` passes each
node manager an `OperationContext` that carries the permit; re-entry
uses the existing context-taking APIs, `PrepareFromCallbackAsync` and
`InheritNodeManagerAdmission` | none | **Behaviour change:** a
context-free call made from a session-close callback, or from the
released `AddReferencesAsync` / `DeleteReferenceAsync` callbacks, no
longer borrows the caller's admission. A removal is deferred to the
background reference drain. An addition or lifecycle change waits for
the admission: awaited inline it blocks until its own cancellation token
fires; started without awaiting it runs after the close. The former
"deletion callback" rejection is gone. To keep such a re-entry from
stalling the lifecycle, node deletion and the deferred reference drain
no longer hold mutation admission while they call the released
reference-removal callbacks (they release it, remove on the deferred
path, and re-queue what is left). One case can still wait: a
context-free add awaited inside an `AddReferencesAsync` callback blocks
that caller until its own cancellation token fires, because a managed
reference add keeps admission across the callback for its atomic
rollback. It does not block later lifecycle commits. |
| Namespace getter decision window (`LifecycleWriter.m_namespaceGetter`)
| A route-preparation thread marker: `NamespaceUris` is read
synchronously, so same-thread re-entry is detected exactly | none | A
getter that registers a serving namespace alias on the preparing thread
is still rejected. A getter that blocks on such a change made on another
thread now deadlocks the publication instead of being rejected. |
`docs/MigrationGuide.md` has a section for each replacement, with
examples. About 110 in-tree call sites and overrides (src, samples,
Applications, tests, perf) moved to the new members; the full solution
builds with no new warnings on net10.0 and net48.
## Remaining slots (kept)
Every remaining `AsyncLocal` in `Opc.Ua.Server` and `Opc.Ua.Types`
carries a `// Ambient (<disposition>): <reason>` comment and a row in
`NativeLifecycleAmbientScopes.csv`. `AmbientScopeInventoryTests`
compares the fields found by reflection with the CSV and fails on a
missing or stale row. `docs/NodeManagers.md` has the disposition table
and the table of removed slots.
| Slot | Why it stays |
|---|---|
| `AsyncCustomNodeManager.m_operationContext`,
`CustomNodeManager2.m_operationContext`, `m_disposeAsyncCoreContext` |
Calls that re-enter from overrides, `NodeState` callbacks or
`DisposeAsyncCore` join the admitted operation; the public manager API
carries no admission token. |
| `AsyncCustomNodeManager.s_permissionReadSnapshot` (#5183) | Crosses
the public `NodeState.OnReadRolePermissions` delegate, which only
receives the system context. |
| `NodeStateModelChangeExtensions.s_isFrameworkBump` | Re-entrancy guard
across the public `OnWriteValue` callback. |
| `ConfigurationNodeManager.m_activeRotationCollector` | Crosses the
pluggable `IPushConfigurationTransactionCoordinator`, whose commit
delegate takes no collector. |
| `UserManagementBinding.m_currentUserChange` | Attributes the
synchronous `IUserManagement.UserDeactivated` event to the change that
raised it. |
| `RestoredQueueStaging.s_current` | Reaches the monitored-item queues
through the released restore callbacks. |
| `NodeState.s_eventPropagation` | Shares one visited set across the
virtual `ReportEvent` recursion. |
| `AmbientMessageContext.s_current` | Deserialization and telemetry
context by design; grants no lifecycle or routing authority. |
`NodeManagerAmbientScope<T>` holds the slot of its owning field and is
not a slot of its own.
Removing the kept slots is tracked in #5222.
## Tests
- Tests that checked a guarantee through a removed slot now check it
through the explicit member (pins, reservations, stealing, generation
binding, nesting, AddNodes reservation, shared physical event bindings,
pinned lookup, callback permits).
- Tests that only checked ambient restore or escaped-context behaviour
of a removed slot were rewritten for the explicit state or deleted.
- New tests cover each obsolete member: an override or caller of only
the obsolete member still works without throwing.
- **net10.0, full `Opc.Ua.Server.Tests` (no LongRunning/Stress):**
12,561 passed, 8 failed, 7 skipped. The 8 are the file-system symlink
tests, which fail on this Windows machine without the symlink privilege;
they are unrelated.
- **net48, NodeManager / History / ContinuationPoint / Session /
Lifecycle / Historian / AmbientScope suites:** 6,494 passed, 1 failed, 1
skipped. The failure is
`WorkerCancellationFailureStillJoinsRetainedDrainAsync(True)`, which
also fails on master net48.
## HistoryRead paging A/B
`perf/ServerLoadHarness --scenario historyread-paging --sessions 8`,
Release net10.0, Server GC, 15 s measured after 8 s warm-up. Master
`8fcdf5b26` vs branch `9f3cfca8e`, both copied to short paths of the
same shape, master and branch alternating each round (order swapped
every round), 5 clean rounds per page size (no round had other processes
above 3 cores). Medians, with the pages/s range:
| Page size | Side | Pages/s | p50 / p99 ms | Server CPU µs / page |
Server alloc B / page |
|---|---|---|---|---|---|
| 100 | master | 66,719 [65,549–68,366] | 0.106 / 0.515 | 116.2 | 37,872
|
| 100 | branch | 66,790 [66,022–68,135] | 0.105 / 0.509 | 114.0 | 38,201
|
| 1000 | master | 15,732 [14,484–15,807] | 0.470 / 1.299 | 420.3 |
312,013 |
| 1000 | branch | 15,236 [15,092–15,646] | 0.477 / 1.491 | 444.7 |
312,379 |
Paired branch/master pages/s ratios: page 100: 1.039, 0.966, 0.999,
1.001, 1.013 (median 1.001); page 1000: 0.993, 0.964, 1.042, 0.990,
0.969 (median 0.990). Both medians are inside the round-to-round spread
(±4 %), so there is no measurable throughput regression. An earlier run
against `5bc97aa6c` showed the branch at or above master in all 5 clean
page-1000 rounds. The branch allocates about 330–370 B more per request:
the request-local and per-callback `OperationContext` copies that keep
overlapping reads and late saves apart.
🤖 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
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.
Summary
N13 of the NodeManager lifetime redesign: namespace default permissions (
DefaultAccessRestrictions,DefaultRolePermissions,DefaultUserRolePermissions) are now cheap to read, and a changed default still applies to the very next check.Two problems, both measured in #5168 (
perf/results/lifecycle-baseline-2026-11-24.md):OperationContext.SetDefaultPermissionscopied the array and appended one element per namespace, andTryGetDefaultPermissionsscanned it linearly. A Read over N namespaces allocated arrays of 1..N and did O(N²) lookups. Inf5-m64-r64, 84 % of server allocation wasNamespaceDefaultPermissions[].BaseVariableState.ReadValueAttributeunder its node lock. Under read load that was 99 % of all lock contention.Change
NamespaceDefaultPermissionCache(new), server-wide, owned byNamespaceMetadataRegistry. It caches the decoded defaults of each namespace whose defaults are static: stored values, no read callbacks, and readable in both access levels. A static decode does not depend on the caller, so every context can share it. Entries are indexed by namespace index in an array that only grows. On each hit the cache checks, without taking a lock:NamespaceDefaultPermissionReader.Generationis unchanged. The registry already moves it on every reported value change of a default property (ClearChangeMasks→StateChanged), on any add, replace or remove of a default property, and on any link, relink or removal of a metadata node. That covers dynamic namespaces and a manager's namespace being removed or reloaded through the lifecycle.Valuechange mask. A value assigned in process withoutClearChangeMasksraises no notification. That namespace is read live until the change is reported, so the change still applies to the next check, as it did before.Server/Namespaceschanges.Detachclears the cache.NamespaceDefaultPermissionReader.Read/ReadAsynclook in the request cache first, then the server cache. They decode only on a miss and fill both caches (the server cache only when the defaults are static).OperationContext). It now holds only caller-dependent (callback) defaults. It is indexed by namespace index: a slot array sized to the highest index seen (up to 64), then aConcurrentDictionary. Each slot is replaced whole, so concurrent validation within one request is safe. It is O(1) per lookup and allocates no more than linearly.MasterNodeManager.NodeManagement.csand the verdict caches are untouched; N6 is in a parallel PR.Tests
NamespaceDefaultPermissionCacheTests(new, ReferenceServer fixture):Clearand growth beyond the initial size.OperationContextDefaultPermissionsCacheTests: 300 namespaces across the slot/dictionary boundary, a generation change, 64k concurrent get/set over 160 namespaces with no cross-namespace result, and disabling drops entries.Opc.Ua.Server.Testsnet10.0: 12316 passed, 10 failed. All 10 are local-environment failures:FileSystemAccessRegressionTestsfailed with a teardown file lock andSimulationRegistryTests.RegisteredLoopFiresAfterStarton a 200 ms timing assertion under load. Both pass when rerun alone.dotnet vstest), with the filter Permission | NamespaceDefault | NamespaceMetadata | AccessRestriction | ConfigurationNodeManagerTests | VerdictCache | ValueReadAuthorization: 331/331 passed.Measurements
#5168 harness, Release net10.0, Server GC, binaries copied to short paths, master
fa144238fvs this branch, alternating order, 3 rounds each, runs with more than 3 foreign cores discarded. Per Read = one 64-node Read request. Means of 3 rounds:f5-m64-r64now allocates 2.3×f5-m64-r1, down from 10.5×.f5-m64-r1is unchanged (+90 B per Read, within noise). A first cut with a fixed 64-slot request array cost +540 B per Read; the array now grows to the highest index seen.ce888ada5(cached role entries are copied on every hit), a new 3-round A/B on a less loaded machine gave:f5-m64-r1: 15.4 → 15.2 KB per Read, 133 µs on both sides.f5-m64-r64: 162.4 → 33.5 KB per Read (2.2× r1), 314 → 280 µs, 26,292 → 28,359 reads/s.lc-ctl(10 sessions × 5 subs × 100 nodes, 4 readers, 8 managers), means of 3 rounds:On master, 99 % of the
lc-ctlcontention came fromBaseVariableState.ReadValueAttributecalled byNamespaceDefaultPermissionReaderfrom monitored-item contexts. That is gone: what remains is ~18 events per 15 s.Reuse for N14
The per-node
DefaultPermissionsChangedsubscription can be replaced by a version stamp.MonitoredNode2subscribes once per monitored node, which is O(monitored nodes) per add/remove. Instead, it can recordNamespaceDefaultPermissionReader.Generationwhen it builds its permission verdicts, and compare it on use, the way the cache entries do. That makes add/remove O(1), and the subscribe/unsubscribe goes away. The global generation alone would make every namespace's verdicts rebuild on any change, and today a cache entry's identity also changes on every global bump, so it is no per-namespace stamp yet. For that,NamespaceDefaultPermissionCachecan keep alongcounter per namespace slot, incremented only when that namespace's decoded defaults differ from the entry they replace, or when its own entry is retired byIsCurrent. Verdicts then hold(namespaceIndex, stamp), and a change to one namespace invalidates only its verdicts. A verdict must also treat "no current cache entry" (callback defaults, or a pending unreported change) as uncacheable, as the entries do, or unreported changes would be missed.🤖 Generated with Claude Code