# Description **Server/core audit fixes with regression tests. Latest review-fix validation, merge validation and earlier acceptance results are distinguished below.** This addresses a 95-finding server/core report. Every finding was reviewed with the OPC UA specification knowledge base or, where the standard does not prescribe a C# implementation, the corresponding ownership/configuration contract. Incorrect or withdrawn subclaims remain qualified rather than being presented as additional fixes. The original checkpoint covers session identity/certificate validation and revocation; certificate/key ownership and transactional updates; TCP reconnect, receive/admission and buffer lifetime; HTTP quotas; subscription admission, durability and pooled payloads; file-operation lifecycle; historian aggregates; fluent/state-machine behavior; and related utilities. It includes targeted regressions and directly related documentation. The approved acceptance cleanup is separate in the commit history: | Cleanup | Verified result | | --- | --- | | Invalid identity-policy and KeyCredential fixture inputs | Fixtures explicitly advertise Username and use its generated policy ID. Credential persistence uses valid clear mode inside the existing encrypted admin context. Original permission, lockout and negative encryption assertions remain. | | Native GDS lifetime and concurrent connection failures | Retain ApplicationInstance until client teardown. A deterministic native reproducer proved the test-only channel cap of 10 was exhausted; removing that override restores the existing bounded default of 1000. No global serialization or production quota change. | | Stress certificate ownership and close accounting | Balance two helper references and the fake transport's server-certificate ownership. Replace the invalid event-count bound with exactly-once physical disposal, opens = closes, zero active entries and one logical entry lifetime. | | Participant deadlines | Use the injected TimeProvider with the existing cross-framework WaitAsync overload. Tests pin one tick before, exact expiry, terminal notification, recovery and timely completion. | | Reproducibility and platform assertions | Preserve canonical WoT bytes/hashes, explicit display-culture contracts and exact numeric-vector assertions. Accept Apple's CryptographicException subtype without weakening disposal balance. | | Missing user-signature proof | Reject null/empty proofs before OS crypto. Return BadUserSignatureInvalid per Part 4, 5.7.3.3. None-policy and valid-signature controls remain. A CI-only test nullable-context error was corrected without changing production behavior. | | Durable sample restore and shared test storage | Dequeue waits for actual batch residency instead of treating failed restore completion as success, and restored files close before deletion. Five deterministic regressions failed before the fix. The two fixtures that clear the shared batch directory are isolated; all original 3,000-item assertions remain unchanged. | ## Latest review follow-up Commit `828856850219518970e8e2f580b8f94b3c1fc748` fixes the deferred robotics disposal reported in the latest review. `RobotIntentNodeManager.DisposeAsync` now joins a shared controller-host drain and then explicitly awaits base node-manager disposal. A controller's bounded shutdown wait may defer its cleanup, but no longer lets the node-manager override finish early. Concurrent callers, including an asynchronous call after synchronous `Dispose`, cannot bypass the drain after the host list has been detached. Synchronous disposal remains nonblocking for deferred work. Deferred initialization failures are logged and retained, and base cleanup failures propagate to asynchronous callers. The existing controller-level bounded disposal contract is unchanged; the node-manager contract is documented in `docs/Robotics.md`. | Regression requirement | Evidence | | --- | --- | | Wait for deferred hosts; preserve synchronous compatibility and concurrent joins | `NodeManagerAsyncDisposalWaitsForDeferredHostsAsync`: four cases covering both entry-point orders and zero/positive host shutdown waits. All four failed before the fix. | | Wait through base cleanup and observe failures | `NodeManagerDisposalWaitsForBaseCleanupAndReportsItsFailureAsync`: four cases hold the actual base-resource semaphore, verify pending callers after the host finishes, then check success or the same propagated exception and exactly-once cleanup. | The focused `IntentHostingCoverageTests` and `IntentControllerHostTests.Dispose` selection passed **30/30 on net10.0 and 30/30 on net48**, with no failures or skips. The final net10 solution build passed with zero errors and only the four previously documented CA2249 warnings in unchanged fuzz-test code. No new warnings, analyzer suppressions, dependencies, or weakened assertions were added. The review thread received a commit-specific reply and was explicitly resolved. This verification is scoped to the robotics feedback; the earlier full Subscriptions-run limitation remains recorded in the merge section below. ## Documentation review follow-up (2026-09-14) Commit `f9a9686fcc5d3cfd19cbbc8c2d826e20f5c7e72f` addresses the six follow-up threads on documentation and implementation rationale. Each has an in-thread reply citing the commit and an explicit resolution. Multiline XML documentation now covers the declarations introduced or modified throughout the entire PR, including internal contracts, samples, tests, and public members of related private helpers. A syntax-aware inventory checked **2,031 declarations across all 256 PR C# paths with zero documentation gaps**. A supplementary check also covers **75 previously unchanged public members** of private helpers involved in the changed code. Token comparison across the conditional-compilation branches proves this follow-up changes **no executable C# or test assertions**. Project-file changes are rationale comments only. The implementation questions are documented at their source: | Question | Resolution | | --- | --- | | Certificate assembly friendship | Server Push configuration reuses the internal explicit-subject CSR helper with the existing key; no public crypto API was added. | | Core.Types assembly friendship | Server builders use internal transition callbacks/revision guards; Server.Tests checks the revision deterministically without creating a public compatibility contract. | | Always-single-reader notifications | One dequeuer preserves event order; optional concurrency fans out within one event and joins before the next event. | | Asynchronous disposal completion | `DisposeAsync` already joins the completion published after admitted operations and all cleanup attempts. The compatibility `Dispose` remains nonblocking to avoid deadlocking an admitted callback against its own drain. | The requested detailed review disposition follows. It distinguishes actual fixes from confirmed policies and incorrect subclaims rather than counting every comment as a new runtime change. ### Detailed disposition of review 5191795284 The [SDK review](https://github.com/OPCFoundation/UA-.NETStandard/pull/4477#pullrequestreview-5191795284) was submitted against `1c4a9df6c`, before the subsequent merge and feedback fixes. Its **15 inline threads** have each received an action-specific reply and an explicit resolution. A fresh GraphQL query verified those replies and resolution states; the fixes in `b8a59990f` remain ancestors of the current branch. | Review concern | Action and disposition | Concrete regression evidence | | --- | --- | --- | | Injected certificate-store providers bypassed | **Fixed.** Registration, configuration snapshots, and validation use the injected providers. Explicit custom types remain authoritative; the built-in Directory catch-all is deferred so native X509 paths and later custom providers are not captured. Failed store opens dispose the created store. | `InjectedProviderResolvesRegisteredAndConfiguredTrustStores` covers default-provider ordering and both registration paths; provider validation/open-failure cases and the unchanged `TrustedCertificateInjectedViaIndependentX509StoreIsObservedAsync` cover real use and independent-store visibility. | | Unguarded timer-thread leadership callbacks | **Fixed.** Each subscriber's exception is logged independently and cannot suppress subsequent subscribers or fail lease operations. `IsLeader` reads the deadline without invoking application callbacks. | `ThrowingLeadershipSubscriberDoesNotFailAcquireOrDisposeAsync`, `ExpiryNotifiesOtherSubscribersWhenOneThrowsAsync`, and `IsLeaderDoesNotDispatchExpiryNotificationsAsync` were all demonstrated failing before the fix. | | Legacy pending-key provider accepts an unfinishable regenerated CSR | **Fixed by explicit capability validation.** A provider implementing only `IPendingCertificateKeyStore` receives `BadNotSupported` before key generation or persistence when regeneration is requested. Existing-key CSR/update remains supported. Regeneration requires matching-only consumption; no unsafe destructive probing was introduced. | `LegacyPendingProviderRejectsRegenerationBeforeCreatingOrSavingAKeyAsync` checks no key or store mutation; `LegacyPendingProviderCompletesExistingKeySigningAndUpdateAsync` proves the supported flow completes. | | Shutdown waits behind user deactivation | **Fixed.** Accepted deactivations drain before the master's lifecycle gate is taken. Configuration retains its binding until the shared drain completes, including concurrent shutdown callers and direct master disposal. | Four cases of `ShutdownDrainsDeactivationOutsideTheSessionClosingGateAsync` exercise real configuration/binding/ServerInternalData/master reentry, retained address space, exact session/subscription closure, and no production cancellation shortcut. | | Subclass cleanup runs under the operation-lifetime lock | **Fixed.** Cleanup starts outside that lock. A pre-published completion joins all disposers, and only the active asynchronous teardown context may use guarded helpers. Captured contexts lose that privilege when the callback exits. | `SynchronousOwnedCleanupLetsSamplingWorkerReachClosedAdmissionAsync`, `DisposeCoreCanUseGuardedMembersWithoutReopeningCallerAdmissionAsync`, captured-context rejection, and exact cleanup-failure/ownership assertions cover both synchronous and suspended cleanup. | | Discovery requestId-zero chunk read after pool return | **Fixed by the earlier merge.** Discovery validation precedes `SaveIntermediateChunk`; no read occurs after that path can return the buffer. The ordering is retained. | `DiscoveryChannelReadsTheFirstChunkBeforeItIsReturnedAsync` uses a poisoning pool and the requestId-zero path. | | T1.8 OPN cleanup misses post-decryption throws | **Fixed by the earlier merge and pinned with new regressions.** Both sequence rejection and certificate mismatch release the decrypted body and input ownership. | `OpenSecureChannelRejectionAfterDecryptionReturnsEveryRentalAsync` checks the exact audit status and pool conservation. Omitting either corresponding release in an isolated snapshot made its case fail; no mutation remains. | | T1.2 mount-root protection depends on the provider | **Fixed at the host boundary.** Separator-only aliases resolve to the protected root. Traversal, empty/whitespace segments, backslashes, and drive/stream qualifiers are rejected before arbitrary providers are invoked. Valid nested paths and root destinations remain supported. | A deliberately permissive provider is used by `NonCanonicalObjectPathsCannotDeleteMoveOrCopyAsync` and invalid-target cases; exact zero-call checks are paired with legitimate nested-path/root-destination controls. | | Inline trusted/issuer entries now face CRL checks | **Intentional strict behavior, documented and tested.** A configured backing store with strict unknown-status rejection requires current revocation information. Explicit-only lists without a store retain their no-store behavior. Actual revocation cannot be suppressed; a matching store entry's policy takes precedence. | `InlineIssuerWithStoreHonorsStrictUnknownRevocationPolicyAsync`, `InlineIssuerRevocationIsNeverSuppressedAsync`, store-precedence cases, and explicit-only controls preserve the missing-information versus actual-revocation distinction in Part 4 6.1.3. | | RSA minimum applied to unspecified ECC identifiers | **Fixed at the application-certificate check.** The RSA minimum is compared only with an actual RSA public key. An unspecified ECC identity is not replaced simply because its key size is below an RSA threshold. | `SilentCertificateCheckPreservesUnspecifiedEccIdentityAsync` checks DER, thumbprint, store contents, and private-key retention; explicit RSA and HTTPS minimum controls remain. | | Failed directory refresh wedges corrective mutations | **Fixed.** Recoverable automatic pre-refresh failures are logged and leave reconciliation pending, but do not block corrective provider mutations. Explicit refresh errors, capacity admission, caller cancellation, and actual provider denials remain enforced. | `CorrectiveDeleteRecoversAfterPersistentOverLimitRefreshFailureAsync` converges an externally over-limit directory back to its exact allowed contents. Capacity, cancellation/token, and six refresh-error controls check negative paths. | | Timed-transition rejection logs at 10 Hz | **Fixed.** Repeated `(state, revision, status)` warnings are deduplicated without changing the retry cadence. A different status or state entry permits another warning. | `RepeatedTimedRejectionLogsOnceAndRecoversAsync` checks one warning over eleven rejections and success on the next attempt. Status-change and same/different-state reentry controls pin reset behavior. | | Bad unsubscribe strands retired-generation bookkeeping | **Fixed.** Retired all-event bookkeeping completes even when unsubscribe reports Bad; the first Bad is still returned to the caller. | Good and BadCommunicationError cases of `RetiredAllEventsDeletionCompletesBookkeepingAndReleasesGenerationAsync` check event/snapshot removal, generation release, and exactly one unsubscribe without finalization replay. | | CSR subject parsing and fallback | **Fixed for existing and regenerated keys.** Omitted subjects fall back to the actual stored certificate. Regeneration resolves the public certificate's subject before creating a key. Malformed or unresolvable subjects return `BadInvalidArgument` before pending-key mutation. | Store-only fallback, real-generator null/empty cases, and missing-subject/malformed-DN controls verify the signed CSR, matching fresh pending key, unchanged active identity, and no destructive side effects. | | Committed RemoveUser change reported as failed | **Fixed for RemoveUser and ModifyUser.** Accepted cleanup is still awaited and close failures remain logged, but cannot replace the committed mutation result. Precommit failures retain their original result and side effects. | `CommittedUserChangeKeepsResultAndPublishedUsersWhenCloseFailsAsync` checks published Users, Good result, logging, and continued closes. `FailedUserChangeKeepsPublishedUsersAndDoesNotCloseSessionsAsync` checks BadNotFound with no publication or close. | | Alleged pooled decoded-request aliasing | **No runtime redesign needed; reviewer rebuttal confirmed.** The decoder copies the relevant input data. Misleading ownership comments were corrected rather than introducing a new dispatch model. | `DecodedRequestRetainsValuesAfterInputBuffersAreReturnedAsync` checks the exact decoded NodeId and ByteString after returned arrays are poisoned. | The current documentation-only follow-up rechecked **104 Core, 473 Server, and 4 Configuration cases** covering these concerns: **581 passed, zero failed or skipped**. The final net10 solution build also passed with **zero warnings and errors**. The complete earlier Core/Server/Configuration and net48 results remain listed separately rather than being presented as rerun current-head acceptance. ## Earlier review follow-up Commit `b8a59990fe2e8e967a12ffd5d9158beed7831143` addresses all 19 review threads. Each thread has an in-thread reply naming this commit and was explicitly resolved after verification; the final paginated query found 19 resolved and zero unresolved threads. The follow-up fixes injected certificate-store selection (including default provider ordering and native X509 paths), actual-RSA minimum enforcement, and CSR capability/subject validation before key mutation. Node-manager teardown uses simpler scoped ownership and drains accepted user revocation outside the master gate; committed user results and retired-event cleanup remain correct when cleanup reports failure. File mutations can recover after failed refresh without bypassing capacity or cancellation, provider paths protect mount roots, and repeated timed rejections no longer flood logs. Leadership subscriber failures are isolated without callbacks from `IsLeader`. Regressions also pin the already-merged OPN/discovery buffer fixes and prove decoded request values do not borrow returned input buffers. The strict inline issuer revocation policy is documented and tested, not weakened. Existing tests were changed only for the reviewed behavior: the incorrect committed-user result was corrected, and inline-issuer/root-alias controls were expanded. ### Review-fix validation | Suite | Scope | Framework | Passed | Existing TRX NotExecuted | | --- | --- | --- | ---: | ---: | | Core | Complete project | net10.0 | 4,970 | 88 | | Server | Complete project | net10.0 | 6,414 | 69 | | Configuration | Complete project | net10.0 | 231 | 0 | | Core | Certificate, lease and buffer compatibility slice | net48 | 153 | 0 | | Server | Reviewed lifecycle, user, file, timer and CSR compatibility slice | net48 | 692 | 0 | | Configuration | Complete project | net48 | 231 | 0 | | CSR provider regressions | Final portable-mock follow-up | net10.0 | 11 | 0 | All runs exited successfully with normal concurrency and leak detection. The Server console reports 5 skips; its TRX additionally records existing assumption/explicit cases, hence the 69-record count above. The Framework build caught two modern-only `ValueTask.CompletedTask` usages in new mock setup; only those expressions changed to the equivalent portable `default(ValueTask)`. The complete modern suites precede that test-only correction; all production files remained byte-identical, and the corrected fixture passed on both targets. The final net10 solution build succeeded with 0 errors and the same 4 CA2249 warnings in unchanged fuzz-test code. Diff checks and changed-line whitespace checks are clean; whole-file formatting still identifies 10 unchanged baseline lines, which were not reformatted outside the feedback scope. The committed 35-file tree was hash-verified against the validation inputs. This is the review-feedback verification scope, not a rerun or sign-off of the historical complete platform/native/soak acceptance campaign below. ## Latest upstream merge Merge `9d9bf679f317164c5b2b90924cd3cdc27a86d451` integrates `master` through `162fc5ebb` (#4486), including the AddNodes child-name index, shared certificate-error reporting, CTT sample-data corrections, and the accompanying regressions and documentation. The CreateSession conflict preserves this branch's certificate ownership, required certificate, application-URI, and channel-certificate checks. The validation result now retains nested errors through `ThrowIfInvalid`, allowing the upstream shared reporting helper to mask trust, policy, and revocation failures consistently without losing audit detail. The new indexed AddNodes regression initially attempted to reuse a deterministic NodeId after renaming its existing node. Renaming frees the BrowseName, not that NodeId. `IndexedBrowseNameReusePreservesExistingNodeIdentityAsync` now proves both contracts: the derived-ID collision leaves the original node intact, then a fresh explicitly requested ID can reuse the old name while the new name remains protected against duplicates. No production identity rule was relaxed. The incoming seeded random-index test uses the existing `UnsecureRandom` wrapper with the same seed and sequence; no new analyzer suppression was added. | Local merge validation | Framework | Passed | Existing exclusions | | --- | --- | ---: | ---: | | Core, complete project | net10.0 | 5,081 | 88 | | NodeState / BaseInstanceState | net10.0 | 579 | 0 | | Server node management, certificate and session-security selection | net10.0 | 112 | 0 | | InformationModel node-management services | net10.0 | 29 | 1 | | NodeState / BaseInstanceState | net48 | 578 | 0 | | Core certificate validation, error reporting and TCP buffers | net48 | 111 | 0 | | Server node management, certificate and session-security selection | net48 | 112 | 0 | All selected runs exited successfully at normal concurrency: **6,602 passing test executions**. Modified test assemblies were explicitly rebuilt, and the combined name/identity regression was verified by name in both net10 and net48 results. No skips or weakened assertions were introduced. The final `dotnet build UA.slnx -c Release --no-restore -m:1` with `CustomTestTarget=net10.0` succeeded with **zero warnings and zero errors**. The resolved source and adjusted tests pass whitespace verification, and their source hashes match the validation inputs. This is merge-specific verification. Earlier review results and the previously reported incomplete full Subscriptions runs below remain scoped to their own commits; they were not reopened or relabeled as passing by this operation. ## Previous upstream merge (2026-09-15 morning) Merge `c4694e20ab089c555af233642042133ff3a03ac8` integrates `master` through `484d6c887`, retaining #4481's shared Like parser/GDS query fixes, #4488's RequestHandle recovery in ServiceFaults, and #4487's expired-session and durable-transfer corrections. Three conflict resolutions preserve both sides: - Alias searches now use the shared `LikePattern` implementation, including upstream malformed-list validation. A timeout overload retains this branch's 100 ms per-alias deadline and `BadTimeout` reporting without keeping a second wildcard translator. The shared matcher's original unlimited overload remains unchanged for existing GDS/ContentFilter callers. New regressions cover bounded prefix/list scans, reuse after timeout, and the alias service result. - Expired activation closes outside the session-manager gate using upstream's once-only timeout claim, audit, and diagnostic accounting. This branch's original-channel and security-policy checks remain in place. - TCP buffer tests retain this branch's ownership, poisoning-pool and post-decryption checks alongside the upstream RequestHandle/fault overload tests; neither set was discarded. The upstream HTTPS binary behavior is intentionally retained: a decoder `ServiceResultException` produces HTTP 200 with an OPC UA ServiceFault carrying the decoder status, response timestamp, and recoverable RequestHandle, rather than the previous HTTP 500 text response. Other exceptions retain their existing HTTP error handling. | Local validation | Framework | Passed | TRX NotExecuted | | --- | --- | ---: | ---: | | Core, complete project | net10.0 | 5,054 | 88 | | Sessions, complete project | net10.0 | 780 | 610 | | Server aliases, expiry/security and subscriptions | net10.0 | 288 | 0 | | GDS database, paging and live directory calls | net10.0 | 263 | 0 | | Shared Like patterns and bounded evaluation | net10.0 | 109 | 0 | | Subscriptions transfer/durability/service selection | net10.0 | 23 | 1 | | HTTPS WebApi, complete project | net10.0 | 346 | 0 | | InformationModel aliases | net10.0 | 54 | 5 | | Shared Like patterns and bounded evaluation | net48 | 109 | 0 | | Core fault handles, TCP/HTTPS and filters | net48 | 268 | 0 | | Server aliases, expiry/security and subscriptions | net48 | 288 | 0 | These selected runs exited successfully with normal test concurrency: **7,582 passing test executions**. Sessions' console reports 379 skips; the TRX also contains conditional/assumption exclusions, so the table uses the actual 610 NotExecuted records. No skips or weakened assertions were added. The new `EvaluationTimeoutBoundsWorkAndPreservesPatternReuse` and `SharedPatternTimeoutRemainsAnAliasServiceError` tests passed on both targets. **Validation limitation:** two unfiltered Subscriptions runs did not produce a final result and were stopped, including a retry with a hang guard. They are not counted as passing. The isolated failover fixture passed 2/2, and the transfer/durability/service selection above passed. The stall's cause was not established; no unrelated code or test was changed to conceal it. The final `dotnet build UA.slnx -c Release --no-restore -m:1` with `CustomTestTarget=net10.0` succeeded with **0 warnings and 0 errors**. Whitespace verification passed for all hand-reconciled files, and staged source hashes match the validation inputs. These are merge-specific checks, not a new full platform/native/soak acceptance sign-off. Earlier review and acceptance evidence below remains dated to its own commit. ## Previous upstream merge (2026-09-14) Merge `c3e09553e4d1509502d4ba751960d58491bea2cf` integrates `master` through `6313e38a0` (#4478), including the CTT-driven Part 13 aggregate corrections and FindAlias argument validation. The upstream tests and CTT documentation are retained. The single conflict in `AliasNameWildcardMatcher` is reconciled through the branch's shared regex compiler: upstream malformed-pattern rejection and `IsValidPattern` coexist with OPC UA character escaping, whole-string/newline matching, the 100 ms timeout, and service-level error reporting. The upstream ReferenceTypeFilter checks and chronological aggregate behavior are preserved. Local merge verification: | Suite / selection | Framework | Passed | Existing skips | | --- | --- | ---: | ---: | | Server aliases, aggregates and historian | net10.0 | 1,011 | 0 | | Server aliases, aggregates and historian | net48 | 1,011 | 0 | | InformationModel aliases | net10.0 | 54 | 5 | | Features aliases | net10.0 | 11 | 0 | | Client aliases | net10.0 | 28 | 0 | | History aggregate/historical-access consumers | net10.0 | 265 | 0 | All selected tests passed at normal concurrency. The final net10 solution build passed with 0 errors and 0 warnings. The resolved file's whitespace check and the staged diff check passed. These are merge-specific checks, not a new full platform/native/soak acceptance claim. ## Previous upstream merges Integrates `master` through `8e874d073`, including the Client, Types, Core and source-generator audit fixes in #4471, #4473, #4474 and #4475, plus the event queue-size revision from #4480. The merge commits are `150ea0439` (26 conflict resolutions) and `a0e17c07c` (the base update that arrived during validation). The overlapping fixes are reconciled rather than replacing either branch: - **Rejected-certificate retention follows this branch, as explicitly requested:** zero means unlimited history; negative values disable new storage while preserving existing backend trimming behavior (Directory clears prior history; shared key/value leaves it intact). The processor and manager policy are not redefined, and documentation/tests describe the distinction. - Preserve owned certificate snapshots and borrowed validation-core lifetimes alongside upstream cache invalidation, store-first CRL checks and `BadCertificateRevocationUnknown` for unsupported revocation lookup. - Combine exactly-once chunk ownership, receive-loop cancellation, stale-epoch rejection and detach-before-adoption with upstream signature-before-padding verification and secret cleanup. - Preserve pooled `HttpClient` per-request configuration together with bounded response reads and deadlines that remain active through body consumption. Regression cases exercise already-used clients and both timeout precedence cases. - Retain the binary-compatible channel-key constructor and normalize omitted profiles; preserve exact profile filtering and upstream binary-first HTTPS/WSS endpoint ordering. - Preserve monotonic lease expiry and stale-confirmation fencing while adding ordered, non-reentrant leadership notifications outside the state lock. ## Validation Local validation of the conflict-resolution merge: | Suite | Framework | Passed | Existing skips | | --- | --- | ---: | ---: | | Core | net10.0 | 4,940 | 88 | | Client | net10.0 | 2,278 | 0 | | Server | net10.0 | 6,088 | 5 | | Types | net10.0 | 10,394 | 1 | | SourceGeneration.Core | net10.0 | 3,940 | 8 | | SourceGeneration | net10.0 | 185 | 0 | | Core | net48 | 4,855 | 104 | After the subsequent four-file #4480 update, the related Server slice passed 811 tests with 5 existing skips, the real durable queue-size cases passed 6/6, and EventManager's 21 cases passed again after analyzer-only expected-array cleanup. The final `dotnet build UA.slnx -c Release` with `CustomTestTarget=net10.0` succeeded: 0 errors and 4 pre-existing CA2249 warnings in unchanged fuzz-test code. Whitespace verification passed for the resolved files and the follow-up. Merge-specific proof includes `RequestTimeoutRemainsActiveWhileReadingTheOpenApiBodyAsync` on already-used shared clients with either the request or HttpClient timeout shorter, the existing ownership/expiry regressions from both branches, and both branches' retention tests adjusted only to the explicitly chosen zero/negative contract. Earlier acceptance at `1c4a9df6c` passed hosted Linux/macOS CI, CodeQL, image builds and the canonical coverage gate (87.15% line, 77.27% branch, 92.14% patch). Both Framework project matrices, all three Windows native suites (183 cases), and the unfiltered net10 stress project (230 cases, including full 60-minute chaos and 30-minute memory soaks) also passed. Those are **pre-merge results**, not a claim that the full framework/platform/native/soak matrix has been rerun on this merge. The previous acceptance workflow remains separate from this review-feedback operation. Security checks, meaningful assertions, leak detection, default native concurrency, full soak durations and coverage thresholds remain intact. The user-set ready-for-review state is unchanged. No architectural or complete merged-head acceptance sign-off is claimed. ## Related Issues - Fixes #4476 ## Checklist - [ ] 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. - [ ] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [x] I have addressed **all** PR feedback received.
31 KiB
Part 16 State Machines
This guide describes the generic, extensible OPC UA Part 16 state-
machine support layered on top of the source-generated ObjectType
proxies and the existing FiniteStateMachineState server base.
For the formal model, see OPC UA Part 16 — State Machines.
Two-mode unified builder
The server side ships one fluent builder — StateMachineBuilder —
with two complementary modes that can be mixed in a single chain:
| Mode | Entry point | Use when … |
|---|---|---|
| Definition | StateMachineBuilder.Create(parent, ctx, nodeId, name) |
You need a state machine that isn't already declared as a generator-emitted *StateMachineState subclass. Declare states, transitions, and cause mappings declaratively. |
| Lifecycle | StateMachineBuilder.For<TState>(stateMachine, ctx) or INodeBuilder<TState>.AsStateMachine() |
You already have a FiniteStateMachineState subclass (stack-shipped, generator-emitted, or vendor) and want to attach behavior (enter/exit/transition hooks, method-to-cause bindings, auto-transitions). |
Both modes share the same lifecycle surface (WithInitialState,
OnEnterState, OnExitState, OnTransition, OnBeforeTransition,
WithCause, WithTimedTransition, ConfigureStateMachine). Async
overloads — OnEnterStateAsync, OnExitStateAsync,
OnTransitionAsync — accept Func<ISystemContext, TState, CancellationToken, ValueTask> (or the four-arg form for transition
observers) and are invoked fire-and-forget on the thread pool
from the synchronous transition path. The handler therefore runs on
a fully-async path (no GetAwaiter().GetResult() / Wait() /
.Result anywhere) without blocking the transition or the calling
client. Exceptions thrown from an async handler are captured and
logged via Debug.WriteLine. Pre-transition guards
(OnBeforeTransition, When*) intentionally remain sync-only
because they must veto the transition synchronously before the
state-machine state mutation completes. The definition methods
(AddState, AddTransition, OnCause, UseElementNamespace) are
only available in definition mode.
Quick reference
| Concern | Client entry point | Server entry point |
|---|---|---|
| Read the current state | StateMachineTypeClient.GetCurrentStateAsync |
FiniteStateMachineState.CurrentState |
| Read current state + last transition (finite) | FiniteStateMachineTypeClient.GetCurrentFiniteStateAsync |
FiniteStateMachineState.LastState/LastTransition |
| Observe transitions (stream) | (Finite)StateMachineTypeClient.ObserveFiniteTransitionsAsync |
n/a |
| Wait for a target state | (Finite)StateMachineTypeClient.WaitForStateAsync |
n/a |
| Enumerate states / transitions | FiniteStateMachineTypeClient.GetAvailableStatesAsync / GetAvailableTransitionsAsync |
n/a |
| Build a state machine declaratively | n/a | StateMachineBuilder.Create (definition mode) |
| Attach behavior to an existing FSM | n/a | StateMachineBuilder.For / INodeBuilder.AsStateMachine (lifecycle mode) |
Client side
The source-generated *TypeClient proxies for state-machine types
(StateMachineTypeClient, FiniteStateMachineTypeClient,
ShelvedStateMachineTypeClient, ExclusiveLimitStateMachineTypeClient,
ProgramStateMachineTypeClient, and any vendor subtypes) all inherit
the generic API automatically — implemented as extension methods
that hang off the proxy base.
Read the current state
var proxy = new ShelvedStateMachineTypeClient(session, conditionId, telemetry);
FiniteStateSnapshot snap = await proxy.GetCurrentFiniteStateAsync(ct);
Console.WriteLine($"State: {snap.CurrentState} ({snap.CurrentStateId})");
Console.WriteLine($"Last transition: {snap.LastTransition} ({snap.LastTransitionId})");
Stream transitions
Pair the proxy with the session's streaming subscription:
ManagedSession session = ...;
IStreamingSubscription streaming = session.DefaultStreaming;
await foreach (FiniteStateSnapshot snap in proxy
.ObserveFiniteTransitionsAsync(streaming, ct: ct))
{
Console.WriteLine($"{snap.Timestamp:O} -> {snap.CurrentState}");
}
Each yielded snapshot is refreshed by reading the four state + transition variables in one round-trip, so consumers see consistent typed data per transition.
Wait for a target state
FiniteStateSnapshot reached = await proxy.WaitForStateAsync(
streaming,
targetStateId: new NodeId(Objects.ShelvedStateMachineType_TimedShelved),
timeout: TimeSpan.FromSeconds(30),
ct: ct);
The wait composes ObserveFiniteTransitionsAsync with timeout and
cancellation; an immediate match against the current state is
short-circuited.
Enumerate states + transitions
IReadOnlyList<FiniteStateInfo> states =
await proxy.GetAvailableStatesAsync(ct);
IReadOnlyList<FiniteTransitionInfo> transitions =
await proxy.GetAvailableTransitionsAsync(ct);
Reads the optional AvailableStates / AvailableTransitions NodeId-array
properties and then reads each referenced node's browse name and number.
An absent or invalid availability property produces an empty result.
Alarm shelving alignment
AlarmClient exposes the same API for the ShelvingState child of
every Part 9 alarm condition:
AlarmClient alarms = session.GetAlarmClient(telemetry);
FiniteStateSnapshot snap = await alarms.GetShelvingStateAsync(conditionId, ct);
await foreach (FiniteStateSnapshot s in alarms
.ObserveShelvingTransitionsAsync(conditionId, streaming, ct: ct))
{
// …
}
Both methods delegate to ShelvedStateMachineTypeClient internally —
same proxy-delegation pattern used by the rest of AlarmClient.
Device Integration (DI) software-update alignment
SoftwareUpdateClient (in Opc.Ua.Di.Client) wraps the same generic
API for each of the four child state machines of OPC 10000-100 §10.3
(PrepareForUpdate, Installation, Confirmation, PowerCycle):
var su = new SoftwareUpdateClient(session, suNodeId, telemetry);
FiniteStateSnapshot? state = await su.GetInstallationStateAsync(ct);
await foreach (FiniteStateSnapshot snap in su
.ObserveInstallationTransitionsAsync(streaming, options: null, ct))
{
// …
}
await su.InstallSoftwarePackageAsync("urn:acme", "2.0.0",
ArrayOf.Empty<string>(), default, ct);
See SoftwareUpdate.md for the full SU
facet — including the server-side OnInstallationStateChanged /
OnPrepareStateChanged / OnConfirmStateChanged instrumentation
hooks that the DI server attaches to its built-in FSM lifecycle.
Vendor extensibility
Vendor concrete state machines declared in a NodeSet (e.g.
MyVendor:FoodPreparationStateMachineType : FiniteStateMachineType)
automatically get the generic API. The proxy generator emits a
FoodPreparationStateMachineTypeClient that inherits from
FiniteStateMachineTypeClient, and every extension method
(GetCurrentFiniteStateAsync, ObserveFiniteTransitionsAsync,
WaitForStateAsync, …) applies through the inheritance chain
transparently. Vendor-declared methods (e.g. BeginPreparation) are
emitted as instance methods on the vendor client by the generator.
Server side — definition mode
Use StateMachineBuilder.Create(...) when you need a state machine
that isn't already a generator-emitted subclass. The builder owns a
FluentFiniteStateMachineState instance, populates its state /
transition / cause tables from your declarations, and freezes the
definition the moment you read StateMachine or attach the first
lifecycle hook.
using Opc.Ua.Server.StateMachines;
FluentFiniteStateMachineState sm = StateMachineBuilder
.Create(parent, systemContext,
nodeId: new NodeId(/*your numeric id*/, namespaceIndex),
browseName: new QualifiedName("PowerSwitch", namespaceIndex))
.AddState(id: 1, "Off", isInitial: true)
.AddState(id: 2, "On")
.AddTransition(id: 10, "OffToOn", from: 1, to: 2)
.AddTransition(id: 20, "OnToOff", from: 2, to: 1)
.OnCause(causeId: 100, from: 1, transition: 10)
.OnCause(causeId: 200, from: 2, transition: 20)
.WithInitialState(1)
.StateMachine;
The builder validates structural integrity at the freeze step (the
first lifecycle method or StateMachine access): every transition's
from/to must reference declared states, every cause mapping must
reference a declared transition, and state / transition / cause ids
must be unique within their tables.
Server side — lifecycle mode
Use StateMachineBuilder.For(...) (or
INodeBuilder<TState>.AsStateMachine() inside a fluent node-manager
build pipeline) when you already have a state-machine instance —
stack-shipped (ShelvedStateMachineState,
ExclusiveLimitStateMachineState, ProgramStateMachineState),
generator-emitted (MyVendor.FoodPreparationStateMachineState), or
the result of an earlier StateMachineBuilder.Create(...) chain.
Stack-shipped state machine
// Existing ShelvedStateMachineState that lives under an alarm condition:
ShelvedStateMachineState shelving = alarm.ShelvingState;
StateMachineBuilder.For(shelving, systemContext)
.OnEnterState(
Objects.ShelvedStateMachineType_TimedShelved,
(ctx, sm) => logger.LogInformation("Alarm timed-shelved"))
.OnExitState(
Objects.ShelvedStateMachineType_TimedShelved,
(ctx, sm) => logger.LogInformation("Alarm un-timed-shelved"))
.OnTransition((ctx, sm, from, to) =>
logger.LogDebug("Shelving {From} -> {To}", from, to))
.WithTimedTransition(
fromStateId: Objects.ShelvedStateMachineType_OneShotShelved,
timeout: TimeSpan.FromMinutes(15),
transitionId: Objects.ShelvedStateMachineType_OneShotShelvedToUnshelved);
The lifecycle builder layers on top of any pre-existing
OnBeforeTransition / OnAfterTransition delegates the state
machine had — the stack-shipped behavior continues to run, with
your handlers wrapping it.
Inside a fluent node-manager build pipeline
[NodeManager]
public partial class MyNodeManager
{
partial void Configure(INodeManagerBuilder builder)
{
builder
.Node(BrowsePaths.SoftwareUpdate.Installation)
.As<DI.InstallationStateMachineState>()
.AsStateMachine()
.OnEnterState(StateNumbers.Installing,
(ctx, sm) => StartInstall(ctx))
.OnTransition((ctx, sm, from, to) =>
_logger.LogInformation("Install: {From} -> {To}", from, to))
.WithTimedTransition(
fromStateId: StateNumbers.Installing,
timeout: TimeSpan.FromMinutes(10),
transitionId: StateNumbers.InstallingToFailed,
causeId: StateNumbers.TimeoutCause);
}
}
AsStateMachine() pulls the ISystemContext from
nodeBuilder.Builder.Context. The INodeBuilder<TState> typed view
ensures the underlying node is a FiniteStateMachineState subclass
at compile time — no runtime casts.
The fluent pipeline retries an expired timed cause on subsequent simulation
ticks if a guard rejects it. It warns only once for an unchanged rejected
state, state revision, and status code; changing the status or entering a
new state revision permits another warning. BadInvalidState remains
silent but resets the previous rejection, so a later different failure is
reported. Warning suppression does not delay retries or prevent recovery
when the guard starts allowing the transition.
Lifecycle ordering
For every transition the dispatcher fires handlers in this order:
DispatchBefore:
builder guards (in registration order)
↓ veto on any failure
[original OnBeforeTransition, if any]
↓ framework state update (LastState ← CurrentState, CurrentState ← newState)
DispatchAfter:
[original OnAfterTransition, if any]
↓
OnExitState(from) (each registered handler, in order)
↓
OnTransition(from, to) (each observer, in order)
↓
OnEnterState(to) (each registered handler, in order)
Builder guards run before any pre-existing
OnBeforeTransition — so they can veto without the original
side-effectful pre-handler running. Builder observers run after
the original OnAfterTransition so stack-shipped audit / change
notifications complete first.
If multiple handlers are registered for the same state or
transition, they fire in the order they were added. Exceptions
thrown by an individual handler do not interrupt the dispatch — they
are caught and logged via Debug.WriteLine.
How the source-generator integrates
- Client: every state-machine
*TypeClientproxy (generated from the standard NodeSet and every vendor NodeSet you feed through the generator) inherits the streaming + read + browse API automatically. No hand-written client per state-machine type. - Server: when a NodeSet declares a concrete subtype of
FiniteStateMachineType(vendor or standard), the generator emits a*StateMachineStateserver class with the hardcodedStateTable/TransitionTable/TransitionMappings/CauseMappingsoverrides. Hook behavior onto that instance viaStateMachineBuilder.For(...)— no need to redeclare the tables.
The unified builder gives you a clean migration path:
- Have a generator-emitted FSM type? Lifecycle mode only. Build
the instance the usual way, then attach behavior with
StateMachineBuilder.For(...). - Need an ad-hoc state machine with no generated subclass?
Definition mode.
StateMachineBuilder.Create(...)constructs aFluentFiniteStateMachineStateand lets you chain definitions and lifecycle hooks in one expression.
Guard clauses (fluent sugar)
The lifecycle builder offers a coarse OnBeforeTransition that
fires for every transition; the When* family provides per-trigger
sugar that compiles down to the same pipeline but scopes the
predicate automatically.
StateMachineBuilder.Create(parent, ctx, nodeId, browseName)
.AddState(1, "Off", isInitial: true)
.AddState(2, "On")
.AddTransition(10, "OffToOn", from: 1, to: 2)
.AddTransition(20, "OnToOff", from: 2, to: 1)
.WhenTransition(10, (ctx, sm) => HasPermission(ctx))
.WhenCause(causeId: 100, (ctx, sm) => sm.SafetyInterlockClear)
.WhenEnter(toStateId: 2, (ctx, sm) => sm.PreflightOk,
denyStatus: StatusCodes.BadInvalidState)
.WhenExit(fromStateId: 2, (ctx, sm) => sm.ShutdownComplete);
| Method | Scope | Available in |
|---|---|---|
OnBeforeTransition(Func<ctx, sm, transitionId, causeId, ServiceResult>) |
Every transition (caller filters) | Both modes |
WhenTransition(transitionId, predicate[, denyStatus]) |
Transition matches transitionId |
Both modes |
WhenCause(causeId, predicate[, denyStatus]) |
Cause matches causeId |
Both modes |
WhenEnter(toStateId, predicate[, denyStatus]) |
Transition would enter toStateId |
Definition mode only |
WhenExit(fromStateId, predicate[, denyStatus]) |
Machine is leaving fromStateId |
Both modes |
Returning false from a predicate vetoes the transition with
BadUserAccessDenied (or the caller-supplied denyStatus).
Multiple guards on the same trigger AND together — the first
predicate returning false wins, and its denyStatus flows
through to DoTransition's return.
All guards (On* + When*) share one pipeline in registration
order — the FIRST failing guard wins. This means a When* guard
declared before an OnBeforeTransition guard runs first.
WhenEnter is definition-mode-only because the builder needs the
transition table to map toStateId to the matching transition ids.
In lifecycle mode the table is protected on the FSM; use
WhenTransition with the explicit transition id instead.
Sub-state machines (hierarchical state)
OPC UA Part 16 §5.2.3 supports nested state machines via the
HasSubStateMachine reference. Standard alarms use this pattern
(ExclusiveLimitAlarmType.LimitState is itself an
ExclusiveLimitStateMachineType distinguishing
HighHigh / High / Low / LowLow while the parent alarm is
Active). Vendor process-control servers compose hierarchical
state machines extensively.
Server side — WithSubStateMachine
The unified builder attaches a sub-state-machine to a parent state.
The dispatcher auto-manages the lifecycle: parent enters → child
activates (and resets to its initial state unless
preserveOnReentry: true is supplied); parent exits → child is
suspended and rejects subsequent transitions until the next
parent re-entry.
FluentFiniteStateMachineState parent = StateMachineBuilder
.Create(parentNode, ctx, parentNodeId, browseName)
.AddState(1, "Active", isInitial: true)
.AddState(2, "Inactive")
.AddTransition(12, "ActiveToInactive", from: 1, to: 2)
.AddTransition(21, "InactiveToActive", from: 2, to: 1)
// Attach a sub-state-machine to the Active parent state.
.WithSubStateMachine(
parentStateId: 1,
browseName: new QualifiedName("LimitState", ns),
configure: child => child
.AddState(10, "HighHigh", isInitial: true)
.AddState(11, "High")
.AddState(12, "Low")
.AddState(13, "LowLow")
.AddTransition(110, "HighHighToHigh", from: 10, to: 11),
preserveOnReentry: false)
.StateMachine;
Available in definition mode only — in lifecycle mode the parent FSM already declares its sub-state machines as part of the type definition. Observe them through the client-side sub-SM accessors below.
WithSubStateMachine and WithInitialState are order-independent:
whichever is called second brings the sub-SM in line with the
parent's current state. (WithInitialState goes through SetState,
which is not a transition and so still runs no user lifecycle
handler — but it does re-arm timed transitions and synchronize
sub-state machines.)
A state declared with isInitial: true is applied automatically when
the machine is created and its state node is materialized as an
InitialStateType (OPC 10000-16 §4.4.10), so the minimal example
above is fully functional without an explicit WithInitialState
call; call WithInitialState to start in a different state. A
sub-state machine's declared initial state is applied only while its
parent is in the attached state.
While suspended, the child FSM's CurrentState and LastTransition
read with Bad_StateNotActive (per OPC 10000-16 §4.4.6), and its
DoTransition / DoCause return BadStateNotActive. The flag is
exposed publicly as FluentFiniteStateMachineState.IsSuspended for
diagnostics.
The resulting address space follows Part 16 §4.4.16 and the standard NodeSets:
LimitAlarm --HasComponent--> Active (StateType)
Active --HasSubStateMachine--> LimitState
LimitAlarm --HasComponent--> LimitState
HasSubStateMachine is a non-hierarchical reference, so it
cannot double as the parent/child reference — the sub-SM is a
HasComponent child of the state machine and the spec reference
hangs off the parent state node.
Server side — materialized state and transition nodes
To give HasSubStateMachine a state node to hang off — and to make
CurrentState/Id and LastTransition/Id resolve to something a
client can actually browse — FluentFiniteStateMachineState
materializes a node per declared state and transition when the machine
is created. All of them are HasComponent children of the machine.
States — one StateType node each, carrying a StateNumber
property equal to the numeric state id. CurrentState/Id points at
the node for the current state and tracks it across transitions, and
the optional AvailableStates property lists them, so
GetAvailableStatesAsync works against a fluent-built server.
Transitions — one TransitionType node each, carrying a
TransitionNumber property and the Part 16 §4.4.11 references:
FromState/ToStateto the two state nodes;HasEffecttoTransitionEventType, unless the transition was declared withhasEffect: false— forward-only, matching how companion NodeSets declare it (the target is a standard node owned by another node manager, so no inverse edge is registered there);HasCauseto the method node, added byWithCause(methodNodeId)for every transition the cause can trigger.
AvailableTransitions lists them, and the optional LastTransition
variable is materialized too — without it the base class has nowhere
to record a completed transition and ObserveFiniteTransitionsAsync
has nothing to subscribe to.
NodeIds are per instance, derived from the machine's own NodeId,
so several machines built from one definition coexist in a single
address space. Use sm.GetStateId(nodeId) / sm.GetTransitionId(nodeId)
and their inverses sm.GetStateNodeId(stateId) /
sm.GetTransitionNodeId(transitionId) to move between a NodeId and
the numeric id used by AddState / AddTransition / OnCause and
the lifecycle hooks — never parse the NodeId's identifier directly.
Element nodes land in the namespace given to UseElementNamespace,
or in the state machine's own namespace when that was not called or
the URI is not registered with the server (the element namespace
defaults to the OPC UA namespace, which must never host vendor
nodes).
Because element NodeIds are derived from browse names, browse names
must be unique across states and transitions (and must not shadow the
standard CurrentState / LastTransition / AvailableStates /
AvailableTransitions children); the builder rejects duplicates when
the definition freezes.
Cost is one node plus one property per declared state and transition, per machine instance — worth weighing for servers that instantiate many machines.
Executable causes
A cause is a Method, and whether it may fire depends on the state the
machine is in. Part 3 §5.7 defines Executable / UserExecutable as
exactly that question, and Part 4 §5.11.2 has Call refuse a Method
that is not executable with Bad_NotExecutable.
WithCause(methodNodeId) therefore answers both attributes from
IsCausePermitted(context, causeId, checkUserAccessRights) alongside
installing the call handler — Executable ignoring user rights,
UserExecutable running the machine's OnCheckUserPermission
callback as well. A client can read them after every transition and
offer only the causes that currently apply, instead of duplicating the
server's state table or calling one to find out.
Pass reportExecutable: false to opt out, for servers that
deliberately keep their methods executable and answer at call time.
The stack-shipped ProgramStateMachineState does the same for its own
Start / Suspend / Resume / Halt / Reset methods when they are
created, so a Program server no longer repeats the wiring per method.
Those five are optional placeholders on the type, so only the ones an
instance declares are wired, matched on browse name alone — a subtype
that redeclares them puts them in its own namespace. Call
WireCauseMethods(context) yourself if you add one to an
already-created instance; Create rebuilds the child list from the
type template, so children added by hand before it are not there when
the automatic pass runs.
Client side — sub-SM observation
FiniteStateMachineTypeClient parent =
new FiniteStateMachineTypeClient(session, alarmId, telemetry);
// The state NodeId comes from AvailableStates ...
IReadOnlyList<FiniteStateInfo> states =
await parent.GetAvailableStatesAsync(ct);
NodeId activeStateId = states.First(s => s.BrowseName.Name == "Active").NodeId;
// ... or from a snapshot's CurrentStateId, to reach the sub-SM of
// whatever state the machine is in right now.
FiniteStateMachineTypeClient? limitSm =
await parent.GetSubStateMachineAsync(
parentStateNodeId: activeStateId, telemetry, ct);
if (limitSm != null)
{
FiniteStateSnapshot snap = await limitSm.GetCurrentFiniteStateAsync(ct);
Console.WriteLine($"Limit state: {snap.CurrentState}");
}
// Observe combined parent + sub-SM transitions:
await foreach (FiniteStateSnapshot snap in parent
.ObserveEffectiveStateAsync(streaming, telemetry, ct: ct))
{
Console.WriteLine($"Parent: {snap.CurrentState}");
if (snap.SubMachine != null)
{
Console.WriteLine($" Sub: {snap.SubMachine.CurrentState}");
}
}
FiniteStateSnapshot gains an optional
SubMachine: FiniteStateSnapshot? field carrying the snapshot of
the parent's currently-active sub-SM (or null if none).
ObserveEffectiveStateAsync yields a combined snapshot each time
either the parent transitions or the parent's currently-active
sub-SM transitions:
- On every parent transition the yield carries the latest known
snapshot of the sub-SM attached to the new state (or
nullif none). - On every sub-SM transition that occurs while the parent is in the state that owns the sub-SM, the yield carries the new sub-SM snapshot. Sub-SM transitions occurring while the parent is in a different state are silently discarded.
Under the hood all discovered sub-SMs are subscribed once up-front and
their notifications are multiplexed through a Channel<T>; sub-SM
events are filtered against the parent's currently-active state.
Client side — typed sub-SM accessors (generated)
For every <opc:Object> child declared on a generator-emitted
ObjectType, the source generator now emits a typed, lazily-resolved
accessor on the parent type's client. For state-machine types, this
gives ergonomic access to known sub-SMs without needing to know the
state NodeId:
// Generated on AlarmConditionTypeClient:
ShelvedStateMachineTypeClient? shelving = await alarm
.GetShelvingStateAsync(telemetry, ct);
// Generated on ExclusiveLimitAlarmTypeClient:
ExclusiveLimitStateMachineTypeClient? limit = await alarm
.GetLimitStateAsync(telemetry, ct);
Properties of the generated accessor:
- Typed — returns the concrete sub-SM proxy type, not the generic
FiniteStateMachineTypeClient. - Lazy — first call resolves the child NodeId via
TranslateBrowsePathsToNodeIdsagainst the parent'sObjectId. Optional children (ModellingRule="Optional") that aren't exposed by the server yieldnull. - Cached — subsequent calls return the same instance without another browse round-trip. The cache is per-parent-instance.
Vendor models that add their own <opc:Object> children on a custom
ObjectType benefit automatically; the generator emits the same shape
for every Object child it encounters.
Fluent builder behavior — HasSubStateMachine is on the state node
Earlier fluent-builder implementations attached HasSubStateMachine to the state machine
root, because the fluent builder did not materialize state nodes.
It now sits on the parent state node per Part 16 §4.4.16, and the
root reference is gone.
Callers that passed the state machine's ObjectId to
GetSubStateMachineAsync must pass a state NodeId instead — from
GetAvailableStatesAsync or from a snapshot's CurrentStateId.
Extensibility recipes
- Add convenience properties. Subclass
FluentFiniteStateMachineState, overrideCreateChildrenif you need vendor-specific child variables, and callStateMachineBuilder.For<MyVendorFsm>(instance, ctx)to attach behavior. - Bind a method node to a cause.
WithCause(methodNodeId)installs anOnCallMethod2handler that callsDoCause(...). The cause id is derived from the method NodeId's numeric identifier (OPC UA convention); the cause→transition mapping is whatever the underlying FSM declared (OnCause(...)in definition mode or hardcoded in a stack/vendor subclass). It also answers the method'sExecutable/UserExecutableattributes fromIsCausePermitted— see Executable causes. - Drive auto-transitions.
WithTimedTransition(fromStateId, timeout, transitionId, causeId)uses the server'sTimeProviderto arm one timer on entry intofromStateId, including the initial state. Re-arming disposes the previous timer. A queued callback cannot transition after reset, replacement, or exit/re-entry.StopTimedTransitions()permanently stops that builder's automatic transitions without removing the machine or its lifecycle observers. Timer-only causes emit transition events, not fabricated Method audit events; real Method calls retain their normal audit events. - Escape hatch.
ConfigureStateMachine(Action<TState>)is invoked synchronously with the underlying state machine. Use it for properties or methods the builder doesn't surface directly.
Transitions are serialized per machine. Before/after handlers retain
per-invocation source and destination snapshots, including nested callbacks.
If a before-handler changes the state, the stale outer transition is rejected
with BadInvalidState. Transition events capture their state data before
after-handlers run, so a nested transition cannot rewrite an earlier event.
Tests
tests/Opc.Ua.Server.Tests/StateMachines/StateMachineBuilderTests.csvalidates definition-mode chaining, validation, and freeze semantics.tests/Opc.Ua.Server.Tests/StateMachines/StateMachineBuilderLifecycleTests.csexercises every lifecycle method, including timed transitions and the layering behavior on top of pre-existing delegates.tests/Opc.Ua.Server.Tests/StateMachines/FluentFiniteStateMachineStateTests.cscovers the table projections.tests/Opc.Ua.Server.Tests/StateMachines/StateMachineBuilderCauseExecutableTests.csandtests/Opc.Ua.Core.Tests/Stack/State/ProgramStateMachineStateTests.cscover theExecutable/UserExecutablereporting of causes.- The Part 9 conformance tests in
tests/Opc.Ua.History.Tests/AlarmsAndConditions*.csexerciseAlarmClient.GetShelvingStateAsyncandObserveShelvingTransitionsAsyncend-to-end against the reference server.
See also
- Subscriptions and Monitored Items — the
IStreamingSubscriptionsurface the observation methods consume. - Alarms and conditions — Part 9 alarm client that exposes the shelving-state-machine helpers.
- Device Integration (DI) software-update facet
— the four DI SU state machines, the typed
SoftwareUpdateClient.StateMachinepartial, and the server-sideOn*StateChangedinstrumentation hooks. - Source-generated NodeManagers —
how vendor NodeSets get their
*TypeClientproxies emitted.