From 5eb962053f6db1e6e99cc1dc8d1887ebbfc09004 Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Sat, 28 Nov 2026 13:22:44 +0100 Subject: [PATCH 1/5] Server: rebase prepared lifecycle batches onto disjoint publications (N12) Concurrent lifecycle commits on disjoint NodeManagers no longer reject each other. A prepared batch is rebased onto the current routing view when its own registrations are unchanged; type, encodeable and namespace/server-URI images merge only the batch's own registrations and reject only overlapping changes. Reference discovery and the conformance read image are recomputed in a bounded loop when a concurrent commit supersedes their view. Genuine conflicts surface as the new public, retryable NodeManagerLifecycleConflictException. Exact-revision captures, initial and shutdown publications keep their strict semantics. lifecycle-reload F3 (4 workers, disjoint managers): master 202-301 reloads and 502-602 failures per 15 s; branch 804-806 reloads, 0 failures. Co-Authored-By: Claude Opus 5.5 --- docs/NodeManagers.md | 55 ++-- .../Lifecycle/IDynamicNodeManagerBatchHost.cs | 7 +- .../NodeManager/Lifecycle/IPreparedChanges.cs | 12 + .../NodeManager/Lifecycle/LifecycleChange.cs | 3 + .../NodeManager/Lifecycle/LifecycleWriter.cs | 7 +- .../Lifecycle/NodeManagerLifecycle.Handoff.cs | 3 +- .../Lifecycle/NodeManagerLifecycle.cs | 253 ++++++++++++++---- .../NodeManagerLifecycleConflictException.cs | 60 +++++ .../NodeManagerRoutingConflictException.cs | 9 +- .../NodeManager/MasterNodeManager.Batch.cs | 28 +- .../Server/ConformanceUnitsManager.cs | 8 +- .../Encoders/EncodeableFactory.Snapshots.cs | 128 ++++++++- src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs | 109 +++++++- src/Opc.Ua.Types/Nodes/TypeTable.cs | 3 + src/Opc.Ua.Types/Utils/NamespaceTable.cs | 31 ++- .../NodeManager/LifecycleWriterTests.cs | 4 +- .../NodeManagerConflictExceptionTests.cs | 77 +++--- .../NodeManagerLifecycleCompatibilityTests.cs | 5 +- ...NodeManagerLifecycleParentContractTests.cs | 2 +- .../NodeManagerLifecycleTests.Batch.cs | 59 +++- ...eManagerLifecycleTests.BindingAdmission.cs | 6 +- .../NodeManagerLifecycleTests.ChangeSet.cs | 17 +- ...gerLifecycleTests.ConcurrentPreparation.cs | 212 +++++++++++++++ .../NodeManagerLifecycleTests.FactoryBatch.cs | 14 +- .../NodeManagerLifecycleTests.Handoff.cs | 14 +- ...ManagerLifecycleTests.NamespaceDecision.cs | 4 +- ...gerLifecycleTests.OptimisticPreparation.cs | 76 +++--- ...odeManagerLifecycleTests.ReferenceBatch.cs | 6 +- ...rLifecycleTests.RetiredBindingAdmission.cs | 4 +- ...anagerLifecycleTests.RoutingReservation.cs | 18 +- .../NodeManagerLifecycleTests.Writer.cs | 4 +- .../EncodeableFactorySnapshotTests.cs | 58 ++++ .../Nodes/TypeTableTests.Snapshots.cs | 109 ++++++++ .../Utils/StringTablePrivateViewTests.cs | 59 ++++ ...AtomicPublicationNativeTests.Boundaries.cs | 2 +- 35 files changed, 1230 insertions(+), 236 deletions(-) create mode 100644 src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycleConflictException.cs create mode 100644 tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ConcurrentPreparation.cs diff --git a/docs/NodeManagers.md b/docs/NodeManagers.md index bdbb867a56..2e92de3ab6 100644 --- a/docs/NodeManagers.md +++ b/docs/NodeManagers.md @@ -1946,36 +1946,37 @@ It preserves serving type relationships, reference names, encoding ownership and A replacement must not reparent a serving type, reuse a reference name or encoding for another type, or change a registered CLR type, XML name or data type definition. Such changes fail before the decision callback; use new type and encoding identifiers for incompatible definitions. -Preparation also requires the same serving identity and revision at commit: even an unrelated -concurrent metadata addition makes the batch stale and requires preparation again. - Preparation captures its serving view and private metadata under the lifecycle writer, then releases the writer before invoking factories, address-space creation, reload participants or NodeId policy preparation. A generation admission protects a current participant while these -callbacks run. Unrelated changes may publish concurrently. Commit rejects a changed serving -view with `InvalidOperationException` before the durable decision; an explicit prepared batch -does not rerun factories or rebase private namespace indexes. - -The compatibility `AddAsync`, `ReloadAsync` and `RemoveAsync` extensions retry a routing-view -conflict caused by an independent publication. Each attempt disposes its uncommitted batch -before preparing against the current view, so private namespace indexes are reconstructed -rather than rebased. An addition or replacement factory may therefore run again; it must -support aborted candidates and repeated construction. Use an explicit prepared batch when -application code must control reconstruction. Only conflicts from that batch's own routing -checks permit retry; a nested explicit batch's failure remains an error of the callback that -invoked it. Factory failures, registration ownership changes and failed aborts remain errors. -The extensions never retry after their decision begins or the batch commits. -They permit at most three attempts. Pass a cancellation token to bound waits -within those attempts. Slot-based change sets and explicit prepared units do -not perform these convenience-adapter retries. - -Commit also releases the writer while discovering monitored-item transitions. The current -generation remains admitted until discovery ends and the writer revalidates the captured view. -A concurrent publication makes the transaction stale before its durable decision is invoked. -Reference-owner discovery also runs outside the writer and host publication semaphores. -It pins the captured view and admits each existing owner callback through that generation's -gate. Reference edits capture each source's version before later owner callbacks run; -publication revalidates the view, contribution map, and source versions before deciding. +callbacks run. Changes on other NodeManagers may publish concurrently, and a batch prepared +before such a publication still commits: commit moves it onto the newer address space instead of +rejecting it. Only what the batch itself prepared is checked against what changed meanwhile: + +- the registrations it replaces or removes must still be current; +- every namespace and server URI index it assigned must still map to the same URI. Two batches + that append different namespaces at the same index conflict; +- every type it registers must still have the serving registration it saw at preparation, and + its supertypes must still exist. The same holds for every encodeable registration it adds; +- reference-owner discovery and the diagnostics conformance image are computed again against the + newer view. They are not a conflict. + +A batch that fails these checks is rejected with `NodeManagerLifecycleConflictException` before the +durable decision callback runs; nothing of it is published. The conflict is retryable: dispose the +rejected batch and prepare the changes again against the current address space. Calling `CommitAsync` +again on the rejected batch does not retry it, and an explicit prepared batch never reruns factories. +Other `InvalidOperationException` failures (factory failures, incompatible type definitions, failed +aborts) are not resolved by a retry. A batch begun from an `ILifecycleCapture` keeps its exact-revision +semantics: any newer publication makes it a `NodeManagerLifecycleConflictException`. + +Commit also releases the writer while discovering monitored-item transitions and reference owners. +The current generation remains admitted until discovery ends and the writer revalidates the view. +Reference-owner discovery runs outside the writer and host publication semaphores. It pins the +view and admits each existing owner callback through that generation's gate. Reference edits +capture each source's version before later owner callbacks run; publication revalidates the view, +contribution map, and source versions before deciding. When another commit publishes during +discovery, discovery runs again against the newer view (up to eight times before the batch is +rejected as a conflict). ```csharp await using IPreparedChanges prepared = await lifecycle.PrepareAsync( diff --git a/src/Opc.Ua.Server/NodeManager/Lifecycle/IDynamicNodeManagerBatchHost.cs b/src/Opc.Ua.Server/NodeManager/Lifecycle/IDynamicNodeManagerBatchHost.cs index 5ccf6dbd5c..bbe3556ecf 100644 --- a/src/Opc.Ua.Server/NodeManager/Lifecycle/IDynamicNodeManagerBatchHost.cs +++ b/src/Opc.Ua.Server/NodeManager/Lifecycle/IDynamicNodeManagerBatchHost.cs @@ -379,6 +379,10 @@ ValueTask DecideAsync( /// The callback permit captured when preparation began, if any. /// The semantic host admission acquired before mutation ownership. /// The transaction's core-publication progress, distinct from the route swap. + /// + /// Whether the type, factory, namespace and server URI images may have moved since preparation. Only the + /// batch's own registrations are merged onto them, and an overlapping change is a conflict. + /// internal sealed record NodeManagerPublicationPlan( ArrayOf Candidates, ArrayOf Removed, @@ -396,7 +400,8 @@ internal sealed record NodeManagerPublicationPlan( PreparedAddressSpaceReferences? References = null, NodeManagerCallbackPermit? CallbackPermit = null, INodeManagerBatchAdmission? Admission = null, - AddressSpacePublisher.PublicationProgress? Progress = null); + AddressSpacePublisher.PublicationProgress? Progress = null, + bool Rebase = false); /// /// Decorates publication and observes dispatch without replacing the bound host or its owners. diff --git a/src/Opc.Ua.Server/NodeManager/Lifecycle/IPreparedChanges.cs b/src/Opc.Ua.Server/NodeManager/Lifecycle/IPreparedChanges.cs index 4593265ccb..dbec30eba2 100644 --- a/src/Opc.Ua.Server/NodeManager/Lifecycle/IPreparedChanges.cs +++ b/src/Opc.Ua.Server/NodeManager/Lifecycle/IPreparedChanges.cs @@ -105,6 +105,9 @@ public interface IPreparedChanges : IAsyncDisposable /// The external durable decision, or null for an in-memory decision. /// Cancels before publication. /// The authoritative committed result. + /// + /// Another publication changed an input of the prepared changes; nothing was published. Prepare again to retry. + /// ValueTask CommitAsync( Func? decideAsync = null, CancellationToken cancellationToken = default); @@ -118,6 +121,9 @@ ValueTask CommitAsync( /// /// Cancels before publication. /// The authoritative committed result. + /// + /// Another publication changed an input of the prepared changes; nothing was published. Prepare again to retry. + /// ValueTask CommitAsync( Func? decideAsync, Action publishCommittedState, @@ -130,6 +136,9 @@ ValueTask CommitAsync( /// Optional application state to install after the routing swap. /// Cancels before publication. /// The authoritative committed result. + /// + /// Another publication changed an input of the prepared changes; nothing was published. Prepare again to retry. + /// ValueTask CommitWithDecisionAsync( Func decideAsync, Action? publishCommittedState = null, @@ -141,6 +150,9 @@ ValueTask CommitWithDecisionAsync( /// The context supplied to the durable decision. /// Cancels before publication. /// The authoritative committed result. + /// + /// Another publication changed an input of the prepared changes; nothing was published. Prepare again to retry. + /// ValueTask CommitInMemoryAsync( NodeManagerDecisionContext decisionContext, CancellationToken cancellationToken); diff --git a/src/Opc.Ua.Server/NodeManager/Lifecycle/LifecycleChange.cs b/src/Opc.Ua.Server/NodeManager/Lifecycle/LifecycleChange.cs index 8fa76d8095..cb4eac80f3 100644 --- a/src/Opc.Ua.Server/NodeManager/Lifecycle/LifecycleChange.cs +++ b/src/Opc.Ua.Server/NodeManager/Lifecycle/LifecycleChange.cs @@ -147,6 +147,9 @@ public static IAsyncNodeManagerFactory AsAsync(this INodeManagerFactory factory) /// The additions, replacements and removals. /// Cancels preparation or the pre-publication decision. /// The authoritative committed result, including any reconciliation issues. + /// + /// Another publication changed an input of the prepared changes; nothing was published. Apply again to retry. + /// /// is null. public static async ValueTask ApplyAsync( this INodeManagerLifecycle lifecycle, diff --git a/src/Opc.Ua.Server/NodeManager/Lifecycle/LifecycleWriter.cs b/src/Opc.Ua.Server/NodeManager/Lifecycle/LifecycleWriter.cs index a41943eccf..0074b6e4f0 100644 --- a/src/Opc.Ua.Server/NodeManager/Lifecycle/LifecycleWriter.cs +++ b/src/Opc.Ua.Server/NodeManager/Lifecycle/LifecycleWriter.cs @@ -596,9 +596,14 @@ internal void ValidateRevision(IServerInternal? server = null) lock (m_state) { PublicationRevision revision = Revision; - if (!revision.IsCurrent() || (server is not null && !revision.MatchesServer(server))) + if (revision.Owner.m_publicationFailed) { throw new InvalidOperationException( + "The NodeManager lifecycle failed after a durable decision; restart the server to recover."); + } + if (!revision.IsCurrent() || (server is not null && !revision.MatchesServer(server))) + { + throw new NodeManagerLifecycleConflictException( "The publication invocation conflicts with a newer address-space revision."); } } diff --git a/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.Handoff.cs b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.Handoff.cs index cf1ff2c8da..c9e4393dff 100644 --- a/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.Handoff.cs +++ b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.Handoff.cs @@ -115,7 +115,8 @@ internal static bool IsSelected(IDynamicNodeManagerHost host, NodeManagerGenerat EnsureSameRunningServer(batch.Server, batch.Host, null); BatchEntry entry = batch.Entries[0]; NodeManagerGeneration predecessor = entry.Current!.Registration.Identity; - if (!ReferenceEquals(batch.Host.RoutingRevision, batch.RoutingRevision) || + // A commit on other managers moves the view without touching the predecessor; the commit rebases it. + if ((!CanRebase(batch) && !ReferenceEquals(batch.Host.RoutingRevision, batch.RoutingRevision)) || !IsSelected(batch.Host, predecessor) || !IsCurrentRegistration(entry.Current.Registration)) { throw new NodeManagerRoutingConflictException( diff --git a/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.cs b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.cs index 27c033a88c..2cd443630e 100644 --- a/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.cs +++ b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.cs @@ -2204,6 +2204,127 @@ void ReleaseAdmissions() } } + /// + /// The number of times a batch is rebased onto a newer serving view before the conflict is reported. + /// + private const int kMaxRebaseAttempts = 8; + + /// + /// Gets whether a batch may move onto a newer serving view. Explicit captures + /// () and startup or shutdown publications require their exact view. + /// + private static bool CanRebase(PreparationPayload batch) + { + return batch.Publication is null && batch.Initial is null && batch.Shutdown is null; + } + + /// + /// Keeps a prepared batch on the current serving view. The caller holds the lifecycle writer. + /// + /// + /// The routing view moves on every commit. A batch depends on it only through the registrations it + /// replaces or removes; node ids are reserved during preparation, and namespaces, server URIs, types + /// and encodeable registrations are checked by their own revisions at publication. Reference discovery + /// and the conformance image are computed against the view the batch is rebased onto. + /// + /// The prepared batch. + /// The diagnostic for a batch that cannot be rebased. + /// + /// A registration of the batch changed, or the batch requires its exact view. + /// + private void RebaseOrReject(PreparationPayload batch, string message) + { + foreach (BatchEntry entry in batch.Entries) + { + if (entry.Current is null) + { + continue; + } + bool current; + lock (m_registrationLock) + { + current = m_registrations.TryGetValue(entry.Current.Registration.Id, out RegistrationState? state) && + ReferenceEquals(state, entry.Current); + } + if (!current) + { + throw new NodeManagerRoutingConflictException( + "A registration changed while the batch was prepared.", batch.RoutingRevision); + } + _ = GetCurrentState( + entry.Current.Registration, + batch.Shutdown is not null, + allowRemovalAfterFailedReadiness: entry.Change.Factory is null); + } + NodeManagerRoutingTable.RoutingSnapshot serving = batch.Host.RoutingRevision; + if (ReferenceEquals(serving, batch.RoutingRevision)) + { + return; + } + if (!CanRebase(batch)) + { + throw new NodeManagerRoutingConflictException(message, batch.RoutingRevision); + } + // Fails fast, before discovery runs again; publication checks the final tables authoritatively. + if (!IsPrefixConsistent(batch.Preparation.NamespaceUris, batch.Server.NamespaceUris) || + !IsPrefixConsistent(batch.Preparation.ServerUris, batch.Server.ServerUris)) + { + throw new NodeManagerRoutingConflictException( + "A namespace or server URI index the batch assigned now identifies another URI.", + batch.RoutingRevision); + } + batch.Rebase(serving); + + static bool IsPrefixConsistent(StringTable prepared, StringTable serving) + { + string[] staged = prepared.ToArray(); + string[] current = serving.ToArray(); + int common = Math.Min(staged.Length, current.Length); + for (int index = 0; index < common; index++) + { + if (!string.Equals(staged[index], current[index], StringComparison.Ordinal)) + { + return false; + } + } + return true; + } + } + + /// + /// Adds the diagnostics conformance image for the batch's current view to its read images. + /// + private static ArrayOf PrepareConformanceReadImages( + PreparationPayload batch, + Dictionary? stagedConformance) + { + ArrayOf readImages = batch.ReadImages; + if (batch.Entries.Count != 0 && stagedConformance is not null && + batch.Server is IConformanceUnitsManagerProvider { ConformanceUnitsManager: { } catalog } && + batch.Server.DiagnosticsNodeManager is DiagnosticsNodeManager diagnostics && + batch.RoutingRevision.TryGetGeneration(diagnostics, out NodeManagerGeneration? diagnosticsOwner)) + { + var retiringGenerations = new HashSet(RefEqualityComparer.Default); + foreach (BatchEntry entry in batch.Entries) + { + if (entry.Current is { } current) + { + retiringGenerations.Add(current.Registration.Identity); + } + } + if (diagnosticsOwner is not null && !retiringGenerations.Contains(diagnosticsOwner)) + { + readImages = + [ + .. readImages, + catalog.PrepareReadImage(diagnostics, batch.RoutingRevision, + retiringGenerations, stagedConformance) + ]; + } + } + return readImages; + } + /// /// Validates or commits a prepared batch: switches routing to the prepared image, retires replaced generations, /// and reports cleanup failures after the commit. @@ -2260,24 +2381,9 @@ void ReleaseAdmissions() } } } - if (!ReferenceEquals( - batch.Host.RoutingRevision, batch.RoutingRevision)) - { - throw new NodeManagerRoutingConflictException( - "The address space changed while the batch was prepared.", batch.RoutingRevision); - } + RebaseOrReject(batch, "The address space changed while the batch was prepared."); foreach (BatchEntry entry in batch.Entries) { - if (entry.Current is not null && - !ReferenceEquals( - GetCurrentState( - entry.Current.Registration, - batch.Shutdown is not null, - allowRemovalAfterFailedReadiness: entry.Change.Factory is null), - entry.Current)) - { - throw new InvalidOperationException("A registration changed while the batch was prepared."); - } if (entry.Current is not null) { NodeManagerGeneration generation = entry.Current.Registration.Identity; @@ -2341,37 +2447,65 @@ void ReleaseAdmissions() batch.Server is IConformanceUnitsManagerProvider { ConformanceUnitsManager: not null } ? ConformanceUnitsManager.StageContributions(candidates) : null; - ArrayOf readImages = batch.ReadImages; - if (batch.Entries.Count != 0 && stagedConformance is not null && - batch.Server is IConformanceUnitsManagerProvider { ConformanceUnitsManager: { } catalog } && - batch.Server.DiagnosticsNodeManager is DiagnosticsNodeManager diagnostics && - batch.RoutingRevision.TryGetGeneration(diagnostics, out NodeManagerGeneration? diagnosticsOwner)) + // Reference discovery runs outside the writer, so a commit on other managers can move the serving + // view meanwhile. The batch is then rebased and discovery repeated against the newer view, which is the + // serial outcome. Only a change of the batch's own inputs is a conflict: its registrations, its namespace + // indexes, or an exact-revision capture. + ArrayOf readImages; + PreparedAddressSpaceReferences? preparedReferences = null; + INodeManagerBatchAdmission? acquiredAdmission = null; + for (int attempt = 1; ; attempt++) { - var retiringGenerations = new HashSet(RefEqualityComparer.Default); - foreach (BatchEntry entry in batch.Entries) + try { - if (entry.Current is { } current) + readImages = PrepareConformanceReadImages(batch, stagedConformance); + preparedReferences = await batch.Host.PrepareReferencesAsync( + candidates, + removed, + batch.RoutingRevision, + cancellationToken, + batch.CallbackPermit).ConfigureAwait(false); + acquiredAdmission = await batch.Host.AcquireCommitAdmissionAsync( + batch.CallbackPermit, cancellationToken).ConfigureAwait(false); + mutation = await m_writer.BeginMutationAsync(cancellationToken).ConfigureAwait(false); + EnsurePublicationServer(batch.Server, batch.Host, batch.Initial, batch.Shutdown, readiness); + if (ReferenceEquals(batch.Host.RoutingRevision, batch.RoutingRevision)) + { + break; + } + if (attempt >= kMaxRebaseAttempts) { - retiringGenerations.Add(current.Registration.Identity); + throw new NodeManagerRoutingConflictException( + "The address space changed while transitions were prepared.", batch.RoutingRevision); } + RebaseOrReject(batch, "The address space changed while transitions were prepared."); } - if (diagnosticsOwner is not null && !retiringGenerations.Contains(diagnosticsOwner)) + catch (NodeManagerRoutingConflictException stale) when ( + stale.StaleDiscovery && acquiredAdmission is null) { - readImages = - [ - .. readImages, - catalog.PrepareReadImage(diagnostics, batch.RoutingRevision, - retiringGenerations, stagedConformance) - ]; + // The host's own discovery observed a newer view (never a nested batch's conflict raised + // inside an owner callback). Rebase under the writer and discover again. + if (attempt >= kMaxRebaseAttempts || !CanRebase(batch)) + { + throw new NodeManagerRoutingConflictException(stale.Message, batch.RoutingRevision); + } + mutation = await m_writer.BeginMutationAsync(cancellationToken).ConfigureAwait(false); + RebaseOrReject(batch, stale.Message); } + catch + { + preparedReferences?.Dispose(); + acquiredAdmission?.Dispose(); + throw; + } + mutation.Dispose(); + preparedReferences?.Dispose(); + preparedReferences = null; + acquiredAdmission?.Dispose(); + acquiredAdmission = null; } - using PreparedAddressSpaceReferences references = - await batch.Host.PrepareReferencesAsync( - candidates, - removed, - batch.RoutingRevision, - cancellationToken, - batch.CallbackPermit).ConfigureAwait(false); + using PreparedAddressSpaceReferences references = preparedReferences!; + using INodeManagerBatchAdmission admission = acquiredAdmission!; foreach (KeyValuePair> deferred in references.DeferredRemovals) { RetiredGeneration? retirement = retired.FirstOrDefault(item => @@ -2383,18 +2517,6 @@ await batch.Host.PrepareReferencesAsync( } retirement.PendingReferences.AddRange(deferred.Value); } - - using INodeManagerBatchAdmission admission = - await batch.Host.AcquireCommitAdmissionAsync( - batch.CallbackPermit, cancellationToken).ConfigureAwait(false); - mutation = await m_writer.BeginMutationAsync(cancellationToken).ConfigureAwait(false); - EnsurePublicationServer(batch.Server, batch.Host, batch.Initial, batch.Shutdown, readiness); - if (!ReferenceEquals( - batch.Host.RoutingRevision, batch.RoutingRevision)) - { - throw new NodeManagerRoutingConflictException( - "The address space changed while transitions were prepared.", batch.RoutingRevision); - } foreach ((NodeManagerGeneration generation, int stripe) in preparationAdmissions) { generation.Gate.Exit(stripe); @@ -2412,8 +2534,8 @@ await batch.Host.AcquireCommitAdmissionAsync( out RegistrationState? current) || !ReferenceEquals(current, entry.Current))) { - throw new InvalidOperationException( - "A registration changed while the batch was prepared."); + throw new NodeManagerRoutingConflictException( + "A registration changed while the batch was prepared.", batch.RoutingRevision); } } @@ -2496,7 +2618,8 @@ await reconciliation.RunAsync( References: references, CallbackPermit: batch.CallbackPermit, Admission: admission, - Progress: batch.PublicationProgress); + Progress: batch.PublicationProgress, + Rebase: CanRebase(batch)); committedReferences = await batch.Host.CommitBatchAsync(context).ConfigureAwait(false); } catch (Exception failure) when ( @@ -3622,9 +3745,20 @@ public PreparationPayload( public int NamespaceCount { get; } /// - /// Gets the serving view that must remain current until publication admission. + /// Gets the serving view the batch is prepared against. It must be current at publication admission. + /// A batch whose own inputs did not change is rebased onto a newer view instead of being rejected. /// - public NodeManagerRoutingTable.RoutingSnapshot RoutingRevision { get; } + public NodeManagerRoutingTable.RoutingSnapshot RoutingRevision { get; private set; } + + /// + /// Moves the batch onto a newer serving view. The caller holds the lifecycle writer and has verified + /// that every registration the batch replaces or removes is still current. + /// + /// The current serving view. + public void Rebase(NodeManagerRoutingTable.RoutingSnapshot current) + { + RoutingRevision = current; + } /// /// Gets the private type tree image of the batch. @@ -4029,7 +4163,12 @@ private async Task CompleteAsync( } catch (Exception failure) when (failure is not OutOfMemoryException) { - executionFailure = failure; + // A stale type, factory, namespace or reference image found before the decision is the + // same retryable conflict as a stale routing view. + executionFailure = failure is OptimisticPublicationConflictException && + !payload.DecisionCommitted && !payload.IsCommitted + ? new NodeManagerLifecycleConflictException(failure.Message, failure) + : failure; } if (!payload.IsCommitted && !payload.DecisionCommitted && diff --git a/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycleConflictException.cs b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycleConflictException.cs new file mode 100644 index 0000000000..67ebadc033 --- /dev/null +++ b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycleConflictException.cs @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2005-2026, OPC Federation AISBL +// SPDX-License-Identifier: MIT + +using System; + +namespace Opc.Ua.Server +{ + /// + /// Reports that prepared lifecycle changes conflict with a change another caller published after they were + /// prepared. Nothing of the rejected changes was published and the durable decision callback did not run. + /// + /// + /// + /// The conflict is retryable: prepare the changes again against the current address space (for example with + /// PrepareAsync or ApplyAsync) and commit + /// the new preparation. Calling CommitAsync again on the rejected preparation + /// does not retry it. + /// + /// + /// Changes that touch disjoint NodeManagers do not conflict: a commit on other managers only moves the batch + /// onto the newer address space. A conflict is reported when another publication replaced or removed a + /// registration the batch changes, appended a different namespace or server URI at an index the batch + /// assigned, registered or removed a type or encodeable type the batch registers, or removed a supertype the + /// batch depends on, and when an explicit no longer matches the address space. + /// + /// + /// Callers can catch this type to tell a retryable conflict from other + /// failures, which a retry does not resolve. + /// + /// + public class NodeManagerLifecycleConflictException : InvalidOperationException + { + /// + /// Initializes the exception with the default conflict message. + /// + public NodeManagerLifecycleConflictException() + : base("The prepared changes conflict with a newer address-space publication.") + { + } + + /// + /// Initializes the exception with a custom message. + /// + /// The error message. + public NodeManagerLifecycleConflictException(string message) + : base(message) + { + } + + /// + /// Initializes the exception with a custom message and the conflict it reports. + /// + /// The error message. + /// The exception that detected the conflict. + public NodeManagerLifecycleConflictException(string message, Exception innerException) + : base(message, innerException) + { + } + } +} diff --git a/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerRoutingConflictException.cs b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerRoutingConflictException.cs index 77c21df0b8..dc25964e7c 100644 --- a/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerRoutingConflictException.cs +++ b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerRoutingConflictException.cs @@ -8,7 +8,7 @@ namespace Opc.Ua.Server /// /// Identifies a captured routing view superseded before a batch's durable decision. /// - internal sealed class NodeManagerRoutingConflictException : InvalidOperationException + internal sealed class NodeManagerRoutingConflictException : NodeManagerLifecycleConflictException { /// /// Creates a conflict for a superseded routing view. @@ -46,6 +46,13 @@ internal NodeManagerRoutingConflictException( routingRevision ?? throw new ArgumentNullException(nameof(routingRevision))); } + /// + /// Gets or sets whether the host's own reference discovery found its view superseded. Only such a conflict + /// lets the batch that started the discovery rebase and discover again; a conflict raised by a nested batch + /// inside an owner callback is never flagged. The flag never leaves the batch that owns the discovery. + /// + internal bool StaleDiscovery { get; init; } + /// /// Gets the live captured routing view checked by the publication host, if available. /// diff --git a/src/Opc.Ua.Server/NodeManager/MasterNodeManager.Batch.cs b/src/Opc.Ua.Server/NodeManager/MasterNodeManager.Batch.cs index 8f7236c919..13648837fa 100644 --- a/src/Opc.Ua.Server/NodeManager/MasterNodeManager.Batch.cs +++ b/src/Opc.Ua.Server/NodeManager/MasterNodeManager.Batch.cs @@ -213,7 +213,10 @@ private async ValueTask PrepareReferencesAsync( { if (!view.TryPin(out int stripe)) { - throw new NodeManagerRoutingConflictException("The reference preparation view has retired.", view); + throw new NodeManagerRoutingConflictException("The reference preparation view has retired.", view) + { + StaleDiscovery = true + }; } try { @@ -234,7 +237,10 @@ private async ValueTask PrepareReferencesAsync( if (!ReferenceEquals(view, m_nodeManagers.Revision)) { throw new NodeManagerRoutingConflictException( - "The address space changed before reference discovery.", view); + "The address space changed before reference discovery.", view) + { + StaleDiscovery = true + }; } ApplyDeferredReferencePrunes(); previous = m_dynamicExternalReferences; @@ -573,9 +579,13 @@ private async ValueTask AcquireUnborrowedAdmissionAs retiringGenerations.Add(generation!); } - typeTree = originalTypes.PrepareAdditiveMerge(typeTree, originalTypes, typeRevision); + // A rebased batch merges only its own registrations onto the serving images; the + // revisions it merged onto are the ones reserved below. + typeTree = originalTypes.PrepareAdditiveMerge( + typeTree, originalTypes, typeRevision, context.Rebase, out typeRevision); factory = originalFactory.PrepareAdditiveMerge( - factory, originalFactory, factoryRevision, context.Preparation.NamespaceUris); + factory, originalFactory, factoryRevision, context.Preparation.NamespaceUris, + context.Rebase, out factoryRevision); PreparedAddressSpaceReferences references = context.References ?? throw new InvalidOperationException("Reference discovery must precede publication."); if (!ReferenceEquals(references.View, m_nodeManagers.Revision) || @@ -610,12 +620,12 @@ private async ValueTask AcquireUnborrowedAdmissionAs using EncodeableFactory.Publication registrations = originalFactory.BeginPublication(originalFactory, factoryRevision); using StringTable.Publication namespaces = Server.NamespaceUris.BeginPublication( - context.Preparation.NamespaceUris, context.Preparation.NamespaceRevision); + context.Preparation.NamespaceUris, context.Preparation.NamespaceRevision, context.Rebase); namespaceReservation = new NamespacePublication( routes, namespaces, context.Preparation.NamespaceUris.ToArray().Skip(Server.NamespaceUris.Count)); using StringTable.Publication serverUris = Server.ServerUris.BeginPublication( - context.Preparation.ServerUris, context.Preparation.ServerRevision); + context.Preparation.ServerUris, context.Preparation.ServerRevision, context.Rebase); foreach (NodeState.ReferenceUpdate update in referenceUpdates) { update.Reserve(); @@ -895,7 +905,11 @@ .. newOwners int stripe = 0; if (generation is not null && !generation.Gate.TryEnter(out stripe)) { - throw new InvalidOperationException("A reference owner retired during discovery."); + throw new NodeManagerRoutingConflictException( + "A reference owner retired during discovery.", view) + { + StaleDiscovery = true + }; } NodeState? node; try diff --git a/src/Opc.Ua.Server/Server/ConformanceUnitsManager.cs b/src/Opc.Ua.Server/Server/ConformanceUnitsManager.cs index a9e966a64e..43e6177dd3 100644 --- a/src/Opc.Ua.Server/Server/ConformanceUnitsManager.cs +++ b/src/Opc.Ua.Server/Server/ConformanceUnitsManager.cs @@ -421,8 +421,12 @@ await diagnostics.PublishConformanceUnitsAsync(units, profiles, cancellationToke { if (!generation.Gate.TryEnter(out int stripe)) { - throw new InvalidOperationException( - "A conformance contributor retired before its generation could be admitted."); + const string retired = + "A conformance contributor retired before its generation could be admitted."; + // A batch's view was superseded by a concurrent commit: the batch rebases and reads again. + throw preparingFrom is not null + ? new NodeManagerRoutingConflictException(retired, preparingFrom) { StaleDiscovery = true } + : new InvalidOperationException(retired); } admissions.Add((generation, stripe)); } diff --git a/src/Opc.Ua.Types/Encoders/EncodeableFactory.Snapshots.cs b/src/Opc.Ua.Types/Encoders/EncodeableFactory.Snapshots.cs index aa0a90a426..9a40af5ca6 100644 --- a/src/Opc.Ua.Types/Encoders/EncodeableFactory.Snapshots.cs +++ b/src/Opc.Ua.Types/Encoders/EncodeableFactory.Snapshots.cs @@ -44,7 +44,8 @@ internal EncodeableFactory CaptureSnapshot(out EncodeableFactory source, out lon return new EncodeableFactory(this) { m_captureSource = new WeakReference(this), - m_captureRevision = m_revision + m_captureRevision = m_revision, + m_capturedMaps = new CapturedMaps(m_encodeableTypes, m_enumeratedTypes, m_xmlNameToType) }; } } @@ -68,6 +69,36 @@ internal EncodeableFactory PrepareAdditiveMerge( EncodeableFactory source, long revision, NamespaceTable namespaceUris) + { + return PrepareAdditiveMerge(additions, source, revision, namespaceUris, rebase: false, out _); + } + + /// + /// Builds compatible additive registration maps without changing either input, optionally rebasing the + /// private registrations onto a newer serving revision. + /// + /// + /// Without the serving revision must still match preparation. With it, a newer + /// revision is accepted when no registration the candidate added or replaced was changed by another + /// publication since the capture; such an overlap is an . + /// Publication must reserve before the durable decision. + /// + /// The privately prepared registrations. + /// The serving factory captured before preparation. + /// The captured serving revision. + /// The namespaces used to compare data type definitions. + /// Whether a newer serving revision may be merged. + /// The serving revision the result was merged onto. + /// The independently owned merged factory. + /// + /// + internal EncodeableFactory PrepareAdditiveMerge( + EncodeableFactory additions, + EncodeableFactory source, + long revision, + NamespaceTable namespaceUris, + bool rebase, + out long mergedRevision) { if (additions is null) { @@ -78,7 +109,9 @@ internal EncodeableFactory PrepareAdditiveMerge( throw new ArgumentNullException(nameof(namespaceUris)); } EncodeableFactory merged = CaptureSnapshot(out EncodeableFactory current, out long currentRevision); - if (!ReferenceEquals(source, current) || revision != currentRevision) + mergedRevision = currentRevision; + bool rebased = revision != currentRevision; + if (!ReferenceEquals(source, current) || (rebased && !rebase)) { throw new OptimisticPublicationConflictException( "Serving factory registrations changed after preparation."); @@ -87,7 +120,45 @@ internal EncodeableFactory PrepareAdditiveMerge( { return merged; } + CapturedMaps? captured = null; + if (rebased) + { + lock (additions.m_publicationGate) + { + captured = additions.m_capturedMaps; + } + if (captured is null) + { + throw new OptimisticPublicationConflictException( + "Serving factory registrations changed after preparation."); + } + } EncodeableFactory proposed = additions.CaptureSnapshot(out _, out _); + if (captured is not null) + { + // Only registrations the candidate added or replaced are merged onto the newer image; another + // publication must not have changed the same keys since the capture. + proposed.m_encodeableTypes = CapturedMaps.Delta(proposed.m_encodeableTypes, captured.EncodeableTypes); + proposed.m_enumeratedTypes = CapturedMaps.Delta(proposed.m_enumeratedTypes, captured.EnumeratedTypes); + proposed.m_xmlNameToType = CapturedMaps.Delta(proposed.m_xmlNameToType, captured.XmlNames); + foreach (ExpandedNodeId key in proposed.m_encodeableTypes.Keys.Concat(proposed.m_enumeratedTypes.Keys)) + { + if (!CapturedMaps.IsUnchanged(captured.EncodeableTypes, merged.m_encodeableTypes, key) || + !CapturedMaps.IsUnchanged(captured.EnumeratedTypes, merged.m_enumeratedTypes, key)) + { + throw new OptimisticPublicationConflictException( + $"Registration '{key}' changed after the batch was prepared."); + } + } + foreach (XmlQualifiedName key in proposed.m_xmlNameToType.Keys) + { + if (!CapturedMaps.IsUnchanged(captured.XmlNames, merged.m_xmlNameToType, key)) + { + throw new OptimisticPublicationConflictException( + $"Registration '{key}' changed after the batch was prepared."); + } + } + } Dictionary structures = merged.m_encodeableTypes .ToDictionary(entry => entry.Key, entry => entry.Value); Dictionary enumerations = merged.m_enumeratedTypes @@ -227,6 +298,58 @@ private void EnsureMutable() /// The serving revision from which these private maps were copied. private long m_captureRevision; + + /// The immutable serving maps this private copy started from, used to rebase it. + private CapturedMaps? m_capturedMaps; + + /// + /// Holds the frozen serving maps of a capture. They are immutable, so holding them costs no copy. + /// + private sealed class CapturedMaps( + FrozenDictionary encodeableTypes, + FrozenDictionary enumeratedTypes, + FrozenDictionary xmlNames) + { + internal FrozenDictionary EncodeableTypes { get; } = encodeableTypes; + + internal FrozenDictionary EnumeratedTypes { get; } = enumeratedTypes; + + internal FrozenDictionary XmlNames { get; } = xmlNames; + + /// + /// Gets the entries of a private map that differ from the captured serving map. + /// + /// The registration key type. + /// The registration type. + internal static FrozenDictionary Delta( + FrozenDictionary proposed, + FrozenDictionary captured) + where TKey : notnull + where TValue : class + { + return proposed + .Where(entry => !captured.TryGetValue(entry.Key, out TValue? value) || + !ReferenceEquals(value, entry.Value)) + .ToFrozenDictionary(entry => entry.Key, entry => entry.Value); + } + + /// + /// Checks that a key maps to the same registration, or is absent, in both images. + /// + /// The registration key type. + /// The registration type. + internal static bool IsUnchanged( + FrozenDictionary captured, + FrozenDictionary current, + TKey key) + where TKey : notnull + where TValue : class + { + return captured.TryGetValue(key, out TValue? before) + ? current.TryGetValue(key, out TValue? after) && ReferenceEquals(before, after) + : !current.ContainsKey(key); + } + } private long m_revision { get => m_storage.Revision; @@ -248,6 +371,7 @@ private bool m_publicationPending internal void BindTo(EncodeableFactory canonical) { m_storage = canonical.m_storage; + m_capturedMaps = null; } /// diff --git a/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs b/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs index a729411721..d4645afc2d 100644 --- a/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs +++ b/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs @@ -38,6 +38,7 @@ private TypeTable CaptureSnapshot( revision = m_revision; var storage = new Storage(); storage.ShareGraphFrom(m_storage); + storage.StagedRegistrations = []; NamespaceTable capturedNamespaces = namespaceUris ?? (copyNamespaceUris ? new NamespaceTable(m_namespaceUris.GetSnapshot(out _).ToArray()!) @@ -142,13 +143,44 @@ TypeInfo Copy(TypeInfo original) /// /// internal TypeTable PrepareAdditiveMerge(TypeTable additions, TypeTable source, long revision) + { + return PrepareAdditiveMerge(additions, source, revision, rebase: false, out _); + } + + /// + /// Builds a compatible additive graph without changing either input, optionally rebasing the private + /// registrations onto a newer serving revision. + /// + /// + /// Without the serving revision must still match preparation. With it, a newer + /// revision is accepted: only the types the candidate registered are merged, and each must still have the + /// serving registration it had when the batch was prepared. A type another publication registered or + /// removed meanwhile, or a supertype that disappeared, is an . + /// Publication must reserve before the durable decision. + /// + /// The privately prepared type graph. + /// The serving table captured before preparation. + /// The captured serving revision. + /// Whether a newer serving revision may be merged. + /// The serving revision the result was merged onto. + /// The independently owned merged graph. + /// + /// + internal TypeTable PrepareAdditiveMerge( + TypeTable additions, + TypeTable source, + long revision, + bool rebase, + out long mergedRevision) { if (additions is null) { throw new ArgumentNullException(nameof(additions)); } TypeTable merged = CaptureSnapshot(out TypeTable current, out long currentRevision); - if (!ReferenceEquals(source, current) || revision != currentRevision) + mergedRevision = currentRevision; + bool rebased = revision != currentRevision; + if (!ReferenceEquals(source, current) || (rebased && !rebase)) { throw new OptimisticPublicationConflictException("Serving types changed after the batch was prepared."); } @@ -156,10 +188,44 @@ internal TypeTable PrepareAdditiveMerge(TypeTable additions, TypeTable source, l { return merged; } + HashSet? only = null; + if (rebased) + { + Dictionary staged; + lock (additions.m_lock) + { + if (additions.m_stagedRegistrations is null || + additions.m_captureSource is null || + !additions.m_captureSource.TryGetTarget(out TypeTable? captured) || + !ReferenceEquals(captured, source) || + additions.m_captureRevision != revision) + { + throw new OptimisticPublicationConflictException( + "Serving types changed after the batch was prepared."); + } + staged = new Dictionary(additions.m_stagedRegistrations); + } + foreach (KeyValuePair registration in staged) + { + long serving = merged.m_nodes.TryGetValue(registration.Key, out TypeInfo? existing) + ? existing.RegistrationVersion + : 0; + if (serving != registration.Value) + { + throw new OptimisticPublicationConflictException( + $"Type '{registration.Key}' changed after the batch was prepared."); + } + } + only = [.. staged.Keys]; + } TypeTable proposed = additions.CaptureSnapshot(out _, out _); merged.EnsureWritableGraph(); foreach (KeyValuePair entry in proposed.m_nodes) { + if (only is not null && !only.Contains(entry.Key)) + { + continue; + } TypeInfo candidate = entry.Value; if (merged.m_nodes.TryGetValue(entry.Key, out TypeInfo? existing)) { @@ -184,6 +250,10 @@ internal TypeTable PrepareAdditiveMerge(TypeTable additions, TypeTable source, l } foreach (KeyValuePair entry in proposed.m_nodes) { + if (only is not null && !only.Contains(entry.Key)) + { + continue; + } TypeInfo candidate = entry.Value; TypeInfo target = merged.m_nodes[entry.Key]; if (candidate.SuperType is { } parent) @@ -194,8 +264,11 @@ internal TypeTable PrepareAdditiveMerge(TypeTable additions, TypeTable source, l { continue; } - throw new InvalidOperationException( - $"Type '{entry.Key}' requires an unavailable supertype '{parent.NodeId}'."); + // The capture had the supertype, so another publication removed it meanwhile. + string missing = $"Type '{entry.Key}' requires an unavailable supertype '{parent.NodeId}'."; + throw only is not null + ? new OptimisticPublicationConflictException(missing) + : new InvalidOperationException(missing); } target.SuperType = superType; superType.AddSubType(target); @@ -235,6 +308,10 @@ internal TypeTable PrepareAdditiveMerge(TypeTable additions, TypeTable source, l } foreach (KeyValuePair encoding in proposed.m_encodings) { + if (only is not null && !only.Contains(encoding.Value.NodeId)) + { + continue; + } if (!merged.m_nodes.TryGetValue(encoding.Value.NodeId, out TypeInfo? target)) { throw new InvalidOperationException( @@ -331,6 +408,11 @@ private void EnsureWritableGraph() private HashSet m_candidateLocalTypes = []; + /// + /// The types a captured table registered privately, with the serving registration version each replaced. + /// + private Dictionary? m_stagedRegistrations => m_storage.StagedRegistrations; + /// The serving revision from which this private graph was copied. private long m_captureRevision; private long m_revision @@ -371,6 +453,21 @@ private bool ShouldRejectCandidateConflict(NodeId typeId) return m_rejectConflictingDefinitions || m_candidateLocalTypes.Contains(typeId); } + /// + /// Records the first private registration of a type in a captured table, with the serving registration + /// version it replaces (zero when the capture did not contain the type). Called under the table lock. + /// + private void TrackStagedRegistration(NodeId typeId) + { + Dictionary? staged = m_stagedRegistrations; + if (staged is not null && !staged.ContainsKey(typeId)) + { + staged.Add( + typeId, + m_nodes.TryGetValue(typeId, out TypeInfo? captured) ? captured.RegistrationVersion : 0); + } + } + private void TrackCandidateType(NodeId typeId) { if (m_captureSource is not null) @@ -392,6 +489,12 @@ internal void Detach() /// private sealed class Storage { + /// + /// The types registered through a captured storage, with the serving registration version each + /// replaced (zero when the capture did not contain the type). Null for serving storage. + /// + internal Dictionary? StagedRegistrations; + /// /// Initializes an empty registration graph. /// diff --git a/src/Opc.Ua.Types/Nodes/TypeTable.cs b/src/Opc.Ua.Types/Nodes/TypeTable.cs index 4bdfe10ec1..5042bc8028 100644 --- a/src/Opc.Ua.Types/Nodes/TypeTable.cs +++ b/src/Opc.Ua.Types/Nodes/TypeTable.cs @@ -565,6 +565,7 @@ public void Add(ILocalNode node) } // create the type info. + TrackStagedRegistration(node.NodeId); m_revision++; if (!m_nodes.TryGetValue(node.NodeId, out TypeInfo? typeInfo)) { @@ -694,6 +695,7 @@ public bool AddEncoding(NodeId dataTypeId, ExpandedNodeId encodingId) } EnsureMutable(); EnsureWritableGraph(); + TrackStagedRegistration(dataTypeId); typeInfo = m_nodes[dataTypeId]; if (typeInfo.Encodings == null) { @@ -752,6 +754,7 @@ private void AddSubtype(NodeId subTypeId, NodeId superTypeId, QualifiedName brow } // create the type info. + TrackStagedRegistration(subTypeId); m_revision++; if (!m_nodes.TryGetValue(subTypeId, out TypeInfo? typeInfo)) { diff --git a/src/Opc.Ua.Types/Utils/NamespaceTable.cs b/src/Opc.Ua.Types/Utils/NamespaceTable.cs index 1270404863..0c9a5a2aa6 100644 --- a/src/Opc.Ua.Types/Utils/NamespaceTable.cs +++ b/src/Opc.Ua.Types/Utils/NamespaceTable.cs @@ -435,13 +435,40 @@ internal StringTable CaptureSnapshot() /// Another publication already reserves the namespace prefix. /// internal Publication BeginPublication(StringTable additions, long revision) + { + return BeginPublication(additions, revision, rebase: false); + } + + /// + /// Reserves the namespace prefix a publication was prepared against and preallocates its additions. + /// + /// + /// Without the table must be unchanged since preparation. With it, entries + /// appended meanwhile are accepted as long as every index the prepared table uses still maps to the same + /// string; two publications that appended different strings at the same index conflict. + /// + /// The prepared table, the captured entries followed by its additions. + /// The revision observed during capture. + /// Whether entries appended after preparation are accepted. + /// + /// The serving namespace prefix changed after preparation. + /// + /// + /// Another publication already reserves the namespace prefix. + /// + internal Publication BeginPublication(StringTable additions, long revision, bool rebase) { string[] proposed = additions.ToArray(); lock (m_syncRoot) { EnsureMutable(); - if (m_version != revision || proposed.Length < m_strings.Count || - !m_strings.SequenceEqual(proposed.Take(m_strings.Count))) + bool consistent = rebase + ? (proposed.Length >= m_strings.Count + ? m_strings.SequenceEqual(proposed.Take(m_strings.Count)) + : proposed.SequenceEqual(m_strings.Take(proposed.Length))) + : m_version == revision && proposed.Length >= m_strings.Count && + m_strings.SequenceEqual(proposed.Take(m_strings.Count)); + if (!consistent) { throw new OptimisticPublicationConflictException("The string table changed after preparation."); } diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/LifecycleWriterTests.cs b/tests/Opc.Ua.Server.Tests/NodeManager/LifecycleWriterTests.cs index db35a1dc35..9afa92dfed 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/LifecycleWriterTests.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/LifecycleWriterTests.cs @@ -249,14 +249,14 @@ public async Task PublicationSessionsCoexistAndOnlyObserveTheirOwnAdvancementAsy { Assert.That(first.IsCurrent, Is.True); Assert.That(second.IsCurrent, Is.False); - Assert.Throws(() => second.ValidateRevision()); + Assert.Throws(() => second.ValidateRevision()); } int preparations = 0; await Assert.ThatAsync(async () => await second.PrepareAsync(() => { preparations++; return new ValueTask(new PublicationCleanup(() => { })); - }).ConfigureAwait(false), Throws.TypeOf()).ConfigureAwait(false); + }).ConfigureAwait(false), Throws.TypeOf()).ConfigureAwait(false); Assert.That(preparations, Is.Zero); _ = await first.PrepareAsync(() => { diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerConflictExceptionTests.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerConflictExceptionTests.cs index 66229ec486..3638cb6d37 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerConflictExceptionTests.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerConflictExceptionTests.cs @@ -1,31 +1,5 @@ -/* ======================================================================== - * Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved. - * - * OPC Foundation MIT License 1.00 - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * The complete license agreement can be found here: - * http://opcfoundation.org/License/MIT/1.00/ - * ======================================================================*/ +// SPDX-FileCopyrightText: Copyright (c) 2005-2026, OPC Federation AISBL +// SPDX-License-Identifier: MIT using System; using System.Reflection; @@ -73,8 +47,9 @@ public async Task PreparedConflictReleasesBatch() CollectTargets(); Assert.That(IsAlive(batch), Is.False); Assert.That(IsAlive(manager), Is.False); - Assert.That(conflict, Is.TypeOf()); - Assert.That(conflict.Message, Does.Contain("Serving types changed")); + Assert.That(conflict, Is.TypeOf()); + Assert.That(conflict.InnerException, Is.TypeOf()); + Assert.That(conflict.Message, Does.Contain("string table changed")); GC.KeepAlive(conflict); } @@ -109,12 +84,17 @@ public async Task CompatibilityRetriesOnlyExactLiveOwnerAsync(string kind, strin { await using var harness = new NodeManagerLifecycleChangeSetCleanupTests.ChangeSetCleanupHarness(); var factory = new EqualFactory("urn:test:native-conflict:" + ownerState); - await using IPreparedChanges prepared = await harness.Lifecycle.PrepareAsync([LifecycleChange.Add(factory)]) - .ConfigureAwait(false); + // A routing conflict needs an exact-revision capture: a plain preparation is rebased onto the view. + await using ILifecycleWriter? writer = kind == "Routing" + ? await harness.Lifecycle.CaptureChanges().BeginAsync().ConfigureAwait(false) + : null; + await using IPreparedChanges prepared = writer is null + ? await harness.Lifecycle.PrepareAsync([LifecycleChange.Add(factory)]).ConfigureAwait(false) + : await writer.PrepareAsync([LifecycleChange.Add(factory)]).ConfigureAwait(false); if (kind == "Prepared") { - harness.Data.TypeTree.AddSubtype( - new NodeId("native-conflict:" + ownerState, 0), DataTypeIds.BaseDataType); + // Appending another namespace at the candidate's private index makes its metadata stale. + harness.Data.NamespaceUris.GetIndexOrAppend("urn:test:native-conflict:other:" + ownerState); } else { @@ -145,8 +125,9 @@ public async Task CompatibilityRetriesOnlyExactLiveOwnerAsync(string kind, strin }).ConfigureAwait(false)).ConfigureAwait(false); Assert.That(second, Is.SameAs(first)); Assert.That(first, kind == "Prepared" - ? Is.TypeOf() + ? Is.TypeOf() : Is.TypeOf()); + Assert.That(first, Is.InstanceOf()); Assert.That(decisions, Is.Zero); Assert.That(factory.CreateCount, Is.EqualTo(1)); Assert.That(factory.DeleteCount, Is.EqualTo(1)); @@ -215,11 +196,15 @@ public async Task CompatibilityDoesNotRetryValueEqualDistinctOwnerAsync(string k var other = new EqualFactory("urn:test:native-conflict:equal:second"); Assert.That(current, Is.EqualTo(other)); Assert.That(current, Is.Not.SameAs(other)); - await using IPreparedChanges prepared = await harness.Lifecycle.PrepareAsync([LifecycleChange.Add(current)]) - .ConfigureAwait(false); + await using ILifecycleWriter? writer = kind == "Routing" + ? await harness.Lifecycle.CaptureChanges().BeginAsync().ConfigureAwait(false) + : null; + await using IPreparedChanges prepared = writer is null + ? await harness.Lifecycle.PrepareAsync([LifecycleChange.Add(current)]).ConfigureAwait(false) + : await writer.PrepareAsync([LifecycleChange.Add(current)]).ConfigureAwait(false); if (kind == "Prepared") { - harness.Data.TypeTree.AddSubtype(new NodeId("equal-owner-conflict", 0), DataTypeIds.BaseDataType); + harness.Data.NamespaceUris.GetIndexOrAppend("urn:test:native-conflict:equal:other"); } else { @@ -235,7 +220,7 @@ public async Task CompatibilityDoesNotRetryValueEqualDistinctOwnerAsync(string k return default; }).ConfigureAwait(false)).ConfigureAwait(false); Assert.That(conflict, kind == "Prepared" - ? Is.TypeOf() + ? Is.TypeOf() : Is.TypeOf()); Assert.That(decisions, Is.Zero); Assert.That(current.CreateCount, Is.EqualTo(1)); @@ -257,8 +242,13 @@ public async Task CompatibilityDoesNotRetryValueEqualDistinctOwnerAsync(string k NodeManagerRoutingTable.RoutingSnapshot? routing = ((IDynamicNodeManagerBatchHost)harness.Master).RoutingRevision; var snapshot = new WeakReference(routing); - IPreparedChanges? prepared = await harness.Lifecycle.PrepareAsync([LifecycleChange.Add(factory)]) - .ConfigureAwait(false); + // A routing conflict needs an exact-revision capture: a plain preparation is rebased onto the view. + await using ILifecycleWriter? writer = metadata + ? null + : await harness.Lifecycle.CaptureChanges().BeginAsync().ConfigureAwait(false); + IPreparedChanges? prepared = writer is null + ? await harness.Lifecycle.PrepareAsync([LifecycleChange.Add(factory)]).ConfigureAwait(false) + : await writer.PrepareAsync([LifecycleChange.Add(factory)]).ConfigureAwait(false); var owner = new WeakReference(prepared); WeakReference manager = factory.Candidate!; CollectTargets(); @@ -267,7 +257,8 @@ public async Task CompatibilityDoesNotRetryValueEqualDistinctOwnerAsync(string k Assert.That(IsAlive(snapshot), Is.True); if (metadata) { - harness.Data.TypeTree.AddSubtype(new NodeId("retention-conflict", 0), DataTypeIds.BaseDataType); + // Appending another namespace at the candidate's private index makes its metadata stale. + harness.Data.NamespaceUris.GetIndexOrAppend("urn:test:native-conflict:retention:other"); } else { @@ -280,7 +271,7 @@ public async Task CompatibilityDoesNotRetryValueEqualDistinctOwnerAsync(string k async () => await prepared.CommitAsync().ConfigureAwait(false)).ConfigureAwait(false) ?? throw new AssertionException("The native unit did not report its conflict."); Assert.That(failure, metadata - ? Is.TypeOf() + ? Is.TypeOf() : Is.TypeOf()); await prepared.DisposeAsync().ConfigureAwait(false); Assert.That(factory.DeleteCount, Is.EqualTo(1)); diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleCompatibilityTests.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleCompatibilityTests.cs index cf8669ec6a..070c2bd343 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleCompatibilityTests.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleCompatibilityTests.cs @@ -289,12 +289,13 @@ public async Task CompatibilityConflictDoesNotHideAbortFailureAsync() candidate.Setup(value => value.DeleteAddressSpaceAsync(It.IsAny())).Throws(failure); IPreparedChanges prepared = await harness.Lifecycle.PrepareAsync([LifecycleChange.Add( NodeManagerLifecycleChangeSetCleanupTests.CreateFactory(candidate))]).ConfigureAwait(false); - harness.Data.TypeTree.AddSubtype(new NodeId("conflict-abort", 0), DataTypeIds.BaseDataType); + // Another namespace at the candidate's private index is a conflict; an unrelated type would be rebased. + harness.Data.NamespaceUris.GetIndexOrAppend("urn:test:native:conflict-abort:other"); AggregateException? observed = await Assert.ThrowsAsync( async () => await prepared.CommitAsync().ConfigureAwait(false)).ConfigureAwait(false); Assert.That(observed!.Flatten().InnerExceptions, Does.Contain(failure)); Assert.That( - observed.Flatten().InnerExceptions.Any(value => value is OptimisticPublicationConflictException), + observed.Flatten().InnerExceptions.Any(value => value is NodeManagerLifecycleConflictException), Is.True); candidate.Verify(value => value.DeleteAddressSpaceAsync(It.IsAny()), Times.Once); candidate.As().Verify(value => value.Dispose(), Times.Never); diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleParentContractTests.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleParentContractTests.cs index fc1c7cd1a6..7f14760072 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleParentContractTests.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleParentContractTests.cs @@ -116,7 +116,7 @@ public async Task CapturedPublicationRevisionRemainsBoundAcrossDeferredInputAcqu .ConfigureAwait(false); Assert.That(publication.IsCurrent, Is.False); await Assert.ThatAsync(() => publication.PrepareAsync([acquiredChange], timeout.Token).AsTask(), - Throws.TypeOf()).ConfigureAwait(false); + Throws.TypeOf()).ConfigureAwait(false); Assert.That(factory.CreateCount, Is.Zero); Task AcquireInputAsync() diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Batch.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Batch.cs index 95b8ce3e29..1ec5f73494 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Batch.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Batch.cs @@ -444,7 +444,7 @@ public async Task PreparedBatchRejectsChangedNamespacePrefixBeforeDecisionAsync( Assert.That(namespaces.GetIndex(kModelNamespaceUri), Is.EqualTo(-1)); ushort concurrent = namespaces.GetIndexOrAppend("urn:opcfoundation.org:Tests:ConcurrentNamespace"); int decisions = 0; - await Assert.ThrowsAsync(async () => + await Assert.CatchAsync(async () => await prepared.CommitAsync(_ => { decisions++; @@ -509,8 +509,12 @@ public async Task PublishedManagerCachesObserveLaterMetadataAndDetachBeforeRetir await AssertReadinessValueAsync(kSecondModelNamespaceUri, kSecondRegistrationValue).ConfigureAwait(false); } + /// + /// A serving type registered after preparation that the batch does not register is not an input of the + /// batch: the commit rebases onto it and keeps it. + /// [Test] - public async Task PreparedBatchRejectsChangedTypeInputsBeforeDecisionAsync() + public async Task PreparedBatchRebasesOntoUnrelatedTypeChangeAsync() { INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; await using IPreparedChanges prepared = await lifecycle.PrepareAsync( @@ -520,17 +524,48 @@ public async Task PreparedBatchRejectsChangedTypeInputsBeforeDecisionAsync() m_server.CurrentInstance.NamespaceUris.GetIndexOrAppend(kModelNamespaceUri)); m_server.CurrentInstance.TypeTree.AddSubtype(unrelated, Ua.ObjectTypeIds.BaseObjectType); int decisions = 0; - await Assert.ThrowsAsync(async () => - await prepared.CommitAsync(_ => - { - decisions++; - return default; - }).ConfigureAwait(false)).ConfigureAwait(false); + await prepared.CommitAsync(_ => + { + decisions++; + return default; + }).ConfigureAwait(false); + Assert.That(decisions, Is.EqualTo(1)); + Assert.That(prepared.IsCommitted, Is.True); + Assert.That(m_server.CurrentInstance.TypeTree.FindSuperType(unrelated), + Is.EqualTo(Ua.ObjectTypeIds.BaseObjectType)); + await AssertReadinessValueAsync(kModelNamespaceUri, kFirstRegistrationValue).ConfigureAwait(false); + } + + /// + /// A type the batch registers that another caller registers after preparation is a changed input: the + /// commit is a retryable conflict before the decision and publishes nothing. + /// + [Test] + public async Task PreparedBatchRejectsChangedTypeInputsBeforeDecisionAsync() + { + INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; + NodeId shared = new(8301, + m_server.CurrentInstance.NamespaceUris.GetIndexOrAppend(kModelNamespaceUri)); + await using IPreparedChanges prepared = await lifecycle.PrepareAsync( + [LifecycleChange.Add(CreateTrackingNodeManagementFactory(kFirstRegistrationValue, manager => + manager.Server.TypeTree.AddSubtype(shared, Ua.ObjectTypeIds.BaseObjectType)))]) + .ConfigureAwait(false); + m_server.CurrentInstance.TypeTree.AddSubtype(shared, Ua.ObjectTypeIds.BaseObjectType); + long registered = ((TypeTable)m_server.CurrentInstance.TypeTree).GetRegistrationVersion(shared); + int decisions = 0; + NodeManagerLifecycleConflictException? conflict = + await Assert.CatchAsync(async () => + await prepared.CommitAsync(_ => + { + decisions++; + return default; + }).ConfigureAwait(false)).ConfigureAwait(false); + Assert.That(conflict?.InnerException, Is.TypeOf()); Assert.That(decisions, Is.Zero); Assert.That(prepared.IsCommitted, Is.False); Assert.That(GetBranchRegistrations(lifecycle).IsEmpty, Is.True); - Assert.That(m_server.CurrentInstance.TypeTree.FindSuperType(unrelated), - Is.EqualTo(Ua.ObjectTypeIds.BaseObjectType)); + Assert.That(((TypeTable)m_server.CurrentInstance.TypeTree).GetRegistrationVersion(shared), + Is.EqualTo(registered)); } [Test] @@ -1182,7 +1217,7 @@ public async Task PreparedBatchRejectsChangedRoutingInputsOverNativeTcp() NodeManagerRegistration intervening = RequireRegistration(publicationResult13.Registrations[0]); int decisions = 0; - await Assert.ThrowsAsync(async () => + await Assert.CatchAsync(async () => await prepared.CommitAsync(_ => { decisions++; @@ -1238,7 +1273,7 @@ public async Task PreparedBatchRejectsChangedRoutingInputsBeforeDecision() NodeManagerRegistration intervening = RequireRegistration(publicationResult14.Registrations[0]); int decisions = 0; - await Assert.ThrowsAsync(async () => + await Assert.CatchAsync(async () => await prepared.CommitAsync(_ => { decisions++; diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.BindingAdmission.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.BindingAdmission.cs index 51d634ec6f..a67f06245d 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.BindingAdmission.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.BindingAdmission.cs @@ -674,7 +674,7 @@ public async Task PreparedBatchAllowsNestedSessionCallbackAddWithoutContextAsync } catch (InvalidOperationException conflict) when (!rejectDecision) { - Assert.That(conflict, Is.TypeOf()); + Assert.That(conflict, Is.TypeOf()); Assert.That(conflict.Message, Is.EqualTo("The publication invocation conflicts with a newer address-space revision.")); Assert.That(factory.CreateCount, Is.Zero); @@ -815,7 +815,7 @@ public async Task PreparedBatchAllowsNestedBindingCallbackAddWithoutContextAsync } catch (InvalidOperationException conflict) { - Assert.That(conflict, Is.TypeOf()); + Assert.That(conflict, Is.TypeOf()); Assert.That(conflict.Message, Is.EqualTo("The publication invocation conflicts with a newer address-space revision.")); Assert.That(callbackFactory.CreateCount, Is.Zero); @@ -1007,7 +1007,7 @@ private async Task VerifyNestedLifecycleCallbackCompletionAsync( } catch (InvalidOperationException conflict) when (!rejectDecision) { - Assert.That(conflict, Is.TypeOf()); + Assert.That(conflict, Is.TypeOf()); Assert.That(conflict.Message, Is.EqualTo("The publication invocation conflicts with a newer address-space revision.")); Assert.That(nestedFactory.CreateCount, Is.Zero); diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ChangeSet.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ChangeSet.cs index f445d1f657..26831a0cd3 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ChangeSet.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ChangeSet.cs @@ -183,7 +183,7 @@ await lifecycle.ApplyAsync( kSecondRegistrationValue, _ => { }, kSecondModelNamespaceUri).CreateAsync); await using ILifecycleWriter invocation = await capture.BeginAsync().ConfigureAwait(false); await Assert.ThatAsync(async () => await invocation.PrepareAsync([LifecycleChange.Add(factory)]) - .ConfigureAwait(false), Throws.TypeOf()).ConfigureAwait(false); + .ConfigureAwait(false), Throws.TypeOf()).ConfigureAwait(false); Assert.That(factory.CreateCount, Is.Zero); Assert.That(invocation.IsCurrent, Is.False); } @@ -254,7 +254,7 @@ public async Task SlotChangeSetResolvesAfterAdmissionAndPreservesExactTargetAsyn else { await Assert.ThatAsync(() => exactPreparation!.WaitAsync(timeout.Token), - Throws.InvalidOperationException).ConfigureAwait(false); + Throws.TypeOf()).ConfigureAwait(false); Assert.That(factory.CreateCount, Is.Zero); Assert.That(lifecycle.Revision, Is.EqualTo(published.Revision)); } @@ -435,7 +435,7 @@ public async Task SlotChangeSetWriterAdvancesOwnUnitsAndRejectsExternalPublicati var factory = new CountingNodeManagerFactory([kModelNamespaceUri], CreateTrackingNodeManagementFactory(kGeneration1Value, _ => { }).CreateAsync); await Assert.ThatAsync(async () => await writer.PrepareAsync([LifecycleChange.Add(factory)]) - .ConfigureAwait(false), Throws.InvalidOperationException).ConfigureAwait(false); + .ConfigureAwait(false), Throws.TypeOf()).ConfigureAwait(false); Assert.That(writer.IsCurrent, Is.False); Assert.That(factory.CreateCount, Is.Zero); } @@ -616,10 +616,10 @@ await lifecycle.ApplyAsync( LifecycleChange acquired = await inputs.WaitAsync(timeout.Token).ConfigureAwait(false); await using ILifecycleWriter writer = await capture.BeginAsync(timeout.Token).ConfigureAwait(false); await Assert.ThatAsync(async () => await writer.PrepareAsync([acquired], timeout.Token) - .ConfigureAwait(false), Throws.InvalidOperationException).ConfigureAwait(false); + .ConfigureAwait(false), Throws.TypeOf()).ConfigureAwait(false); await Assert.ThatAsync(async () => await writer.ValidateAsync( [acquired], (_, _) => default, timeout.Token).ConfigureAwait(false), - Throws.InvalidOperationException).ConfigureAwait(false); + Throws.TypeOf()).ConfigureAwait(false); Assert.That(writer.IsCurrent, Is.False); Assert.That(factory.CreateCount, Is.Zero); @@ -1597,7 +1597,8 @@ public async Task SlotChangeSetStaleCommitDisposesCandidateAndDrainsOperationBef LifecycleWriter writer = harness.Writer; Assert.That(writer.ActiveOperationCount, Is.Zero); - Mock candidate = CreateManager(kNamespaceUri); + // Both additions append a different namespace at the same index, so the prepared one is stale. + Mock candidate = CreateManager(kNamespaceUri + ":candidate"); int candidateFactoryCalls = 0; var candidateFactory = CreateFactory(candidate, () => candidateFactoryCalls++); IPreparedChanges prepared = await lifecycle.PrepareAsync( @@ -1606,7 +1607,7 @@ public async Task SlotChangeSetStaleCommitDisposesCandidateAndDrainsOperationBef try { LifecycleResult winner = await lifecycle.ApplyAsync( - [LifecycleChange.Add(CreateFactory(CreateManager(kNamespaceUri)))]) + [LifecycleChange.Add(CreateFactory(CreateManager(kNamespaceUri + ":winner")))]) .ConfigureAwait(false); await winner.Retired.ConfigureAwait(false); using (Assert.EnterMultipleScope()) @@ -1623,7 +1624,7 @@ public async Task SlotChangeSetStaleCommitDisposesCandidateAndDrainsOperationBef decisions++; return default; }).ConfigureAwait(false)).ConfigureAwait(false); - Assert.That(stale, Is.TypeOf()); + Assert.That(stale, Is.InstanceOf()); InvalidOperationException? repeated = await Assert.CatchAsync( async () => await prepared.CommitAsync(_ => { diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ConcurrentPreparation.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ConcurrentPreparation.cs new file mode 100644 index 0000000000..8b2a1736dc --- /dev/null +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ConcurrentPreparation.cs @@ -0,0 +1,212 @@ +// SPDX-FileCopyrightText: Copyright (c) 2005-2026, OPC Federation AISBL +// SPDX-License-Identifier: MIT + +using System; +using System.Threading; +using System.Threading.Tasks; +using NUnit.Framework; +using Opc.Ua.Server.RuntimeNodeSet; + +namespace Opc.Ua.Server.Tests.NodeManager +{ + /// + /// Prepared changes on disjoint NodeManagers commit after each other; overlapping changes are rejected with a + /// retryable before the decision. + /// + public sealed partial class NodeManagerLifecycleTests + { + /// + /// A reload prepared before a reload of another manager publishes is rebased and commits. + /// + [Test] + public async Task PreparedReloadCommitsAfterDisjointReloadPublishesAsync() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; + NodeManagerSlot first = await AddRuntimeManagerAsync( + lifecycle, kModelNamespaceUri, kFirstRegistrationValue, timeout.Token).ConfigureAwait(false); + NodeManagerSlot second = await AddRuntimeManagerAsync( + lifecycle, kSecondModelNamespaceUri, kSecondRegistrationValue, timeout.Token).ConfigureAwait(false); + + await using IPreparedChanges prepared = await lifecycle.PrepareAsync( + [LifecycleChange.Reload(first, RuntimeFactory(kModelNamespaceUri, 303))], timeout.Token) + .ConfigureAwait(false); + LifecycleResult intervening = await lifecycle.ApplyAsync( + [LifecycleChange.Reload(second, RuntimeFactory(kSecondModelNamespaceUri, 404))], timeout.Token) + .ConfigureAwait(false); + int decisions = 0; + LifecycleResult committed = await prepared.CommitAsync(_ => + { + decisions++; + return default; + }, timeout.Token).ConfigureAwait(false); + + using (Assert.EnterMultipleScope()) + { + Assert.That(decisions, Is.EqualTo(1)); + Assert.That(prepared.IsCommitted, Is.True); + Assert.That(committed.Revision, Is.GreaterThan(intervening.Revision)); + Assert.That(first.TryGetCurrent(out NodeManagerSlotSnapshot current), Is.True); + Assert.That(current.Generation, Is.EqualTo(2)); + Assert.That(second.TryGetCurrent(out NodeManagerSlotSnapshot other), Is.True); + Assert.That(other.Generation, Is.EqualTo(2)); + } + await AssertReadinessValueAsync(kModelNamespaceUri, 303).ConfigureAwait(false); + await AssertReadinessValueAsync(kSecondModelNamespaceUri, 404).ConfigureAwait(false); + } + + /// + /// An addition of a new namespace prepared before an unrelated reload publishes is rebased and commits. + /// + [Test] + public async Task PreparedAdditionCommitsAfterDisjointReloadPublishesAsync() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; + NodeManagerSlot first = await AddRuntimeManagerAsync( + lifecycle, kModelNamespaceUri, kFirstRegistrationValue, timeout.Token).ConfigureAwait(false); + + await using IPreparedChanges prepared = await lifecycle.PrepareAsync( + [LifecycleChange.Add(RuntimeFactory(kSecondModelNamespaceUri, kSecondRegistrationValue))], + timeout.Token).ConfigureAwait(false); + await lifecycle.ApplyAsync( + [LifecycleChange.Reload(first, RuntimeFactory(kModelNamespaceUri, 303))], timeout.Token) + .ConfigureAwait(false); + LifecycleResult committed = await prepared.CommitAsync(cancellationToken: timeout.Token) + .ConfigureAwait(false); + + Assert.That(committed.Registrations.Count, Is.EqualTo(1)); + await AssertReadinessValueAsync(kModelNamespaceUri, 303).ConfigureAwait(false); + await AssertReadinessValueAsync(kSecondModelNamespaceUri, kSecondRegistrationValue).ConfigureAwait(false); + } + + /// + /// Two reloads prepared for the same slot overlap: the second commit is a retryable conflict that publishes + /// nothing, and preparing it again succeeds. + /// + [Test] + public async Task OverlappingReloadOfSameSlotIsRetryableConflictAsync() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; + NodeManagerSlot slot = await AddRuntimeManagerAsync( + lifecycle, kModelNamespaceUri, kFirstRegistrationValue, timeout.Token).ConfigureAwait(false); + + await using IPreparedChanges stale = await lifecycle.PrepareAsync( + [LifecycleChange.Reload(slot, RuntimeFactory(kModelNamespaceUri, 303))], timeout.Token) + .ConfigureAwait(false); + await lifecycle.ApplyAsync( + [LifecycleChange.Reload(slot, RuntimeFactory(kModelNamespaceUri, 505))], timeout.Token) + .ConfigureAwait(false); + int decisions = 0; + await Assert.ThatAsync(async () => await stale.CommitAsync(_ => + { + decisions++; + return default; + }, timeout.Token).ConfigureAwait(false), Throws.InstanceOf()) + .ConfigureAwait(false); + using (Assert.EnterMultipleScope()) + { + Assert.That(decisions, Is.Zero); + Assert.That(stale.IsCommitted, Is.False); + } + await AssertReadinessValueAsync(kModelNamespaceUri, 505).ConfigureAwait(false); + + await lifecycle.ApplyAsync( + [LifecycleChange.Reload(slot, RuntimeFactory(kModelNamespaceUri, 303))], timeout.Token) + .ConfigureAwait(false); + await AssertReadinessValueAsync(kModelNamespaceUri, 303).ConfigureAwait(false); + } + + /// + /// Two additions that append different namespaces at the same index overlap: the second commit is a + /// retryable conflict that publishes nothing, and preparing it again succeeds. + /// + [Test] + public async Task OverlappingNamespaceAdditionIsRetryableConflictAsync() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; + int namespaceCount = m_server.CurrentInstance.NamespaceUris.Count; + + await using IPreparedChanges stale = await lifecycle.PrepareAsync( + [LifecycleChange.Add(RuntimeFactory(kModelNamespaceUri, kFirstRegistrationValue))], timeout.Token) + .ConfigureAwait(false); + await AddRuntimeManagerAsync( + lifecycle, kSecondModelNamespaceUri, kSecondRegistrationValue, timeout.Token).ConfigureAwait(false); + await Assert.ThatAsync( + async () => await stale.CommitAsync(cancellationToken: timeout.Token).ConfigureAwait(false), + Throws.InstanceOf()).ConfigureAwait(false); + using (Assert.EnterMultipleScope()) + { + Assert.That(stale.IsCommitted, Is.False); + Assert.That(m_server.CurrentInstance.NamespaceUris.GetIndex(kModelNamespaceUri), Is.LessThan(0)); + Assert.That( + m_server.CurrentInstance.NamespaceUris.GetIndex(kSecondModelNamespaceUri), + Is.EqualTo(namespaceCount)); + } + + await AddRuntimeManagerAsync( + lifecycle, kModelNamespaceUri, kFirstRegistrationValue, timeout.Token).ConfigureAwait(false); + await AssertReadinessValueAsync(kModelNamespaceUri, kFirstRegistrationValue).ConfigureAwait(false); + await AssertReadinessValueAsync(kSecondModelNamespaceUri, kSecondRegistrationValue).ConfigureAwait(false); + } + + /// + /// Concurrent reloads of disjoint managers all commit. + /// + [Test] + public async Task ConcurrentReloadsOfDisjointManagersAllCommitAsync() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60)); + INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; + NodeManagerSlot first = await AddRuntimeManagerAsync( + lifecycle, kModelNamespaceUri, kFirstRegistrationValue, timeout.Token).ConfigureAwait(false); + NodeManagerSlot second = await AddRuntimeManagerAsync( + lifecycle, kSecondModelNamespaceUri, kSecondRegistrationValue, timeout.Token).ConfigureAwait(false); + const int rounds = 8; + + await Task.WhenAll( + ReloadAsync(first, kModelNamespaceUri, 1000), + ReloadAsync(second, kSecondModelNamespaceUri, 2000)).ConfigureAwait(false); + + using (Assert.EnterMultipleScope()) + { + Assert.That(first.TryGetCurrent(out NodeManagerSlotSnapshot current), Is.True); + Assert.That(current.Generation, Is.EqualTo(rounds + 1)); + Assert.That(second.TryGetCurrent(out NodeManagerSlotSnapshot other), Is.True); + Assert.That(other.Generation, Is.EqualTo(rounds + 1)); + } + await AssertReadinessValueAsync(kModelNamespaceUri, 1000 + rounds - 1).ConfigureAwait(false); + await AssertReadinessValueAsync(kSecondModelNamespaceUri, 2000 + rounds - 1).ConfigureAwait(false); + + async Task ReloadAsync(NodeManagerSlot slot, string namespaceUri, int baseValue) + { + for (int round = 0; round < rounds; round++) + { + await using IPreparedChanges prepared = await lifecycle.PrepareAsync( + [LifecycleChange.Reload(slot, RuntimeFactory(namespaceUri, baseValue + round))], + timeout.Token).ConfigureAwait(false); + await Task.Yield(); + await prepared.CommitAsync(cancellationToken: timeout.Token).ConfigureAwait(false); + } + } + } + + private static RuntimeNodeSetNodeManagerFactory RuntimeFactory(string namespaceUri, int value) + { + return new RuntimeNodeSetNodeManagerFactory(CreateOptions(namespaceUri, value)); + } + + private static async Task AddRuntimeManagerAsync( + INodeManagerLifecycle lifecycle, + string namespaceUri, + int value, + CancellationToken cancellationToken) + { + LifecycleResult added = await lifecycle.ApplyAsync( + [LifecycleChange.Add(RuntimeFactory(namespaceUri, value))], cancellationToken).ConfigureAwait(false); + return added.Registrations[0].Slot; + } + } +} diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.FactoryBatch.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.FactoryBatch.cs index 8877af53df..4ae3f32278 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.FactoryBatch.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.FactoryBatch.cs @@ -966,8 +966,12 @@ public async Task PreparedBatchSchemaResolverChangesOnlyOnPublicationAsync(bool Assert.That(holder.TryResolve(structure, out _), Is.EqualTo(publish)); } + /// + /// An encodeable registration made after preparation under a key the batch does not register is not an + /// input of the batch: the commit merges the batch's registrations onto it and keeps it. + /// [Test] - public async Task PreparedBatchRejectsChangedFactoryBeforeDecisionAsync() + public async Task PreparedBatchRebasesOntoUnrelatedFactoryChangeAsync() { INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; await using IPreparedChanges prepared = await lifecycle.PrepareAsync( @@ -979,15 +983,15 @@ public async Task PreparedBatchRejectsChangedFactoryBeforeDecisionAsync() ExpandedNodeId alias = new(8305, "urn:opcfoundation.org:Tests:ConcurrentFactory"); factory.Builder.AddEncodeableType(alias, type).Commit(); int decisions = 0; - await Assert.ThatAsync(() => prepared.CommitAsync(_ => + await prepared.CommitAsync(_ => { decisions++; return default; - }).AsTask(), Throws.TypeOf()).ConfigureAwait(false); - Assert.That(decisions, Is.Zero); + }).ConfigureAwait(false); + Assert.That(decisions, Is.EqualTo(1)); Assert.That(factory.TryGetEncodeableType(alias, out IEncodeableType? retained), Is.True); Assert.That(retained, Is.SameAs(type)); - Assert.That(prepared.IsCommitted, Is.False); + Assert.That(prepared.IsCommitted, Is.True); } [TestCase(false)] diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Handoff.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Handoff.cs index 87d34e8664..16abc73c12 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Handoff.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Handoff.cs @@ -75,8 +75,12 @@ await lifecycle.ApplyAsync([LifecycleChange.Replace(original.Slot, factory)], ti } } + /// + /// A publication on another manager while the predecessor drains does not make the successor stale: the + /// handoff is rebased and commits. + /// [Test] - public async Task HandoffWorkerAllowsUnrelatedPublicationAndRejectsStaleSuccessorAsync() + public async Task HandoffWorkerAllowsUnrelatedPublicationAndCommitsSuccessorAsync() { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var lifecycle = (NodeManagerLifecycle)m_server.NodeManagerLifecycle; @@ -102,11 +106,11 @@ public async Task HandoffWorkerAllowsUnrelatedPublicationAndRejectsStaleSuccesso Assert.That(pause.Finished.Task.IsCompleted, Is.False); pause.AllowDrain.TrySetResult(true); - Assert.That(await pause.Finished.Task.WaitAsync(timeout.Token).ConfigureAwait(false), Is.True); - Assert.That(lifecycle.Revision, Is.EqualTo(unrelated.Revision)); + Assert.That(await pause.Finished.Task.WaitAsync(timeout.Token).ConfigureAwait(false), Is.False); + Assert.That(lifecycle.Revision, Is.EqualTo(unrelated.Revision + 1)); Assert.That(predecessor.Slot.TryGetCurrent(out NodeManagerSlotSnapshot current), Is.True); - Assert.That(current.NodeManager, Is.SameAs(predecessor.NodeManager)); - Assert.That(current.Generation, Is.EqualTo(predecessor.Generation)); + Assert.That(current.NodeManager, Is.Not.SameAs(predecessor.NodeManager)); + Assert.That(current.Generation, Is.EqualTo(predecessor.Generation + 1)); } finally { diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.NamespaceDecision.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.NamespaceDecision.cs index 0d5c500d80..eb30bfa7e6 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.NamespaceDecision.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.NamespaceDecision.cs @@ -179,7 +179,7 @@ public Task NamespaceRegistrationSurvivesDecisionCancellationAsync( } /// - /// An unrelated namespace change before reservation still invalidates an already prepared batch. + /// An alias namespace appended before reservation at the index a prepared batch assigned invalidates it. /// [TestCase(false)] [TestCase(true)] @@ -214,7 +214,7 @@ public async Task NamespaceMutationBeforeReservationRejectsStalePreparedBatchAsy master.RegisterNamespaceManager(AliasUri, manager); } NodeManagerRoutingTable.RoutingSnapshot changed = host.RoutingRevision; - await Assert.ThrowsAsync(async () => + await Assert.CatchAsync(async () => { await prepared.CommitAsync(_ => { diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.OptimisticPreparation.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.OptimisticPreparation.cs index 3ae27fc65f..4170e21736 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.OptimisticPreparation.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.OptimisticPreparation.cs @@ -163,7 +163,7 @@ public async Task CompatibilityAdditionRepreparesAfterRepeatedIndependentPublica } long revision = lifecycle.Revision; int decisions = 0; - await Assert.ThrowsAsync(async () => await prepared.CommitAsync(_ => + await Assert.CatchAsync(async () => await prepared.CommitAsync(_ => { decisions++; return default; @@ -213,7 +213,7 @@ public async Task CompatibilityAdditionRetriesAfterServingNamespaceChangesDuring return innerFactory.CreateAsync(server, configuration, token); }); - await Assert.ThrowsAsync(async () => await lifecycle.ApplyAsync( + await Assert.CatchAsync(async () => await lifecycle.ApplyAsync( [LifecycleChange.Add(factory.Object)], timeout.Token).ConfigureAwait(false)).ConfigureAwait(false); Assert.That(factoryCalls, Is.EqualTo(1)); LifecycleResult publicationResult1 = await CommitChangeAsync( @@ -277,10 +277,10 @@ await Assert.ThatAsync( } /// - /// A serving type-tree revision change during candidate creation is retried by the compatibility API. + /// An unrelated serving type registered during candidate creation does not make the batch stale. /// [Test] - public async Task CompatibilityAdditionRetriesAfterServingTypeTreeChangesDuringPreparationAsync() + public async Task AdditionRebasesOntoServingTypeTreeChangesDuringPreparationAsync() { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; @@ -302,22 +302,21 @@ public async Task CompatibilityAdditionRetriesAfterServingTypeTreeChangesDuringP return innerFactory.CreateAsync(server, configuration, token); }); - await Assert.ThrowsAsync(async () => await lifecycle.ApplyAsync( - [LifecycleChange.Add(factory.Object)], timeout.Token).ConfigureAwait(false)).ConfigureAwait(false); - Assert.That(factoryCalls, Is.EqualTo(1)); - LifecycleResult publicationResult2 = await CommitChangeAsync( - lifecycle, LifecycleChange.Add(factory.Object), timeout.Token).ConfigureAwait(false); - NodeManagerRegistration registration = RequireRegistration(publicationResult2.Registrations[0]); + LifecycleResult added = await lifecycle.ApplyAsync( + [LifecycleChange.Add(factory.Object)], timeout.Token).ConfigureAwait(false); + NodeManagerRegistration registration = RequireRegistration(added.Registrations[0]); - Assert.That(factoryCalls, Is.EqualTo(2)); + Assert.That(factoryCalls, Is.EqualTo(1)); Assert.That(lifecycle.Registrations.ToList(), Does.Contain(registration)); + Assert.That(m_server.CurrentInstance.TypeTree.FindSuperType(new NodeId(99001)), + Is.EqualTo(ObjectTypeIds.BaseObjectType)); } /// - /// A serving encodeable-factory revision change during candidate creation is retried by the compatibility API. + /// An unrelated serving encodeable registration made during candidate creation does not make the batch stale. /// [Test] - public async Task CompatibilityAdditionRetriesAfterServingFactoryChangesDuringPreparationAsync() + public async Task AdditionRebasesOntoServingFactoryChangesDuringPreparationAsync() { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; @@ -345,15 +344,14 @@ public async Task CompatibilityAdditionRetriesAfterServingFactoryChangesDuringPr return innerFactory.CreateAsync(server, configuration, token); }); - await Assert.ThrowsAsync(async () => await lifecycle.ApplyAsync( - [LifecycleChange.Add(factory.Object)], timeout.Token).ConfigureAwait(false)).ConfigureAwait(false); - Assert.That(factoryCalls, Is.EqualTo(1)); - LifecycleResult publicationResult3 = await CommitChangeAsync( - lifecycle, LifecycleChange.Add(factory.Object), timeout.Token).ConfigureAwait(false); - NodeManagerRegistration registration = RequireRegistration(publicationResult3.Registrations[0]); + LifecycleResult added = await lifecycle.ApplyAsync( + [LifecycleChange.Add(factory.Object)], timeout.Token).ConfigureAwait(false); + NodeManagerRegistration registration = RequireRegistration(added.Registrations[0]); - Assert.That(factoryCalls, Is.EqualTo(2)); + Assert.That(factoryCalls, Is.EqualTo(1)); Assert.That(lifecycle.Registrations.ToList(), Does.Contain(registration)); + Assert.That(m_server.CurrentInstance.Factory.TryGetEncodeableType(new ExpandedNodeId(99002), out _), + Is.True); } /// @@ -588,21 +586,34 @@ public async Task ReferenceDiscoveryDoesNotHoldWriterOrLeakOwnerAdmissionAsync(s cancellation.Cancel(); } release.TrySetResult(true); - await Assert.ThatAsync(() => pending.WaitAsync(timeout.Token), - outcome == "Cancel" ? Throws.InstanceOf() : - outcome == "Failure" ? Throws.TypeOf() : - Throws.TypeOf()).ConfigureAwait(false); + if (outcome == "Retire") + { + // The removed owner never held the source, so discovery against the newer view finds the + // same (no) owner: the batch is rebased and commits, as it would after the removal. + await pending.WaitAsync(timeout.Token).ConfigureAwait(false); + } + else + { + await Assert.ThatAsync(() => pending.WaitAsync(timeout.Token), + outcome == "Cancel" ? Throws.InstanceOf() : + outcome == "Failure" ? Throws.TypeOf() : + Throws.InstanceOf()).ConfigureAwait(false); + } } LifecycleResult committed = RequireLifecycleValue(independentResult); await committed.Retired.WaitAsync(timeout.Token).ConfigureAwait(false); + bool rebased = outcome == "Retire"; using (Assert.EnterMultipleScope()) { - Assert.That(decisions, Is.Zero); - Assert.That(publication.IsCommitted, Is.False); - Assert.That(lifecycle.Revision, Is.EqualTo(committed.Revision)); - Assert.That(m_server.CurrentInstance.NamespaceUris.GetIndex(kSecondModelNamespaceUri), Is.EqualTo(-1)); + Assert.That(decisions, Is.EqualTo(rebased ? 1 : 0)); + Assert.That(publication.IsCommitted, Is.EqualTo(rebased)); + Assert.That(lifecycle.Revision, Is.EqualTo(committed.Revision + (rebased ? 1 : 0))); + Assert.That(m_server.CurrentInstance.NamespaceUris.GetIndex(kSecondModelNamespaceUri), + rebased ? Is.GreaterThanOrEqualTo(0) : Is.EqualTo(-1)); } - owner.Verify(value => value.GetManagerHandleAsync(source, It.IsAny()), Times.Once); + // A stale view is discovered again once before publication rejects the taken namespace index. + owner.Verify(value => value.GetManagerHandleAsync(source, It.IsAny()), + outcome == "Stale" ? Times.Between(1, 2, Moq.Range.Inclusive) : Times.Once()); async ValueTask ResolveAsync(CancellationToken token) { @@ -736,7 +747,7 @@ await Assert.ThatAsync(() => outer.CommitAsync(_ => { decisions++; return default; - }, timeout.Token).AsTask(), Throws.TypeOf()).ConfigureAwait(false); + }, timeout.Token).AsTask(), Throws.InstanceOf()).ConfigureAwait(false); await outer.DisposeAsync().ConfigureAwait(false); using (Assert.EnterMultipleScope()) { @@ -829,7 +840,8 @@ async ValueTask FailPreparationAsync(CancellationToken token) } /// - /// Candidate callbacks do not serialize unrelated publication, and a stale candidate is never rebased. + /// Candidate callbacks do not serialize unrelated publication, and a candidate whose namespace index was taken + /// meanwhile is rejected without rerunning its factory. /// [TestCase(false)] [TestCase(true)] @@ -890,7 +902,7 @@ await Assert.ThatAsync(() => stale.CommitAsync(_ => { decisions++; return default; - }, timeout.Token).AsTask(), Throws.TypeOf()).ConfigureAwait(false); + }, timeout.Token).AsTask(), Throws.InstanceOf()).ConfigureAwait(false); Assert.That(stale.IsCommitted, Is.False); Assert.That(decisions, Is.Zero, "A conflicting preparation must fail before any durable decision."); } diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ReferenceBatch.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ReferenceBatch.cs index 7d5499ab56..70abf20c61 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ReferenceBatch.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ReferenceBatch.cs @@ -1259,7 +1259,7 @@ public async Task ConcurrentPublicationDoesNotDeadlockSessionClosingReentryAsync } catch (InvalidOperationException conflict) when ( conflict is NodeManagerRoutingConflictException || - (conflict.GetType() == typeof(InvalidOperationException) && + (conflict.GetType() == typeof(NodeManagerLifecycleConflictException) && conflict.Message == "The publication invocation conflicts with a newer address-space revision.")) { @@ -1525,7 +1525,7 @@ public async Task SessionClosingReentryDuringDurableDecisionWaitsForWriterReleas } catch (InvalidOperationException conflict) { - Assert.That(conflict, Is.TypeOf()); + Assert.That(conflict, Is.TypeOf()); Assert.That(conflict.Message, Is.EqualTo( "The publication invocation conflicts with a newer address-space revision.")); @@ -2187,7 +2187,7 @@ ValueTask DecideAsync(CancellationToken _) if (removeContributor) { await Assert.ThatAsync(() => prepared.CommitAsync(DecideAsync, timeout.Token).AsTask(), - Throws.TypeOf() + Throws.TypeOf() .With.Message.StartsWith("Serving references changed during preparation.")) .ConfigureAwait(false); Assert.That(decisions, Is.Zero); diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.RetiredBindingAdmission.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.RetiredBindingAdmission.cs index 2855ef2b7a..f37611a2a7 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.RetiredBindingAdmission.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.RetiredBindingAdmission.cs @@ -365,7 +365,7 @@ public async Task PreparedImmediateRetirementFinishesAdmittedEventMutationAsync( release.TrySetResult(true); await Task.WhenAll(commit, mutation).WaitAsync(TimeSpan.FromSeconds(10), timeout.Token) .ConfigureAwait(false); - InvalidOperationException? stale = await Assert.ThrowsAsync( + InvalidOperationException? stale = await Assert.ThrowsAsync( async () => await pendingAdd.WaitAsync(TimeSpan.FromSeconds(10), timeout.Token) .ConfigureAwait(false)).ConfigureAwait(false); adding = null; @@ -510,7 +510,7 @@ public async Task PreparedRetirementLetsAdmittedSessionReleaseItsNotificationLea await Task.WhenAll(commit, activation).WaitAsync(TimeSpan.FromSeconds(10), timeout.Token) .ConfigureAwait(false); session = await activation.ConfigureAwait(false); - InvalidOperationException? stale = await Assert.ThrowsAsync( + InvalidOperationException? stale = await Assert.ThrowsAsync( async () => await pendingAdd.WaitAsync(TimeSpan.FromSeconds(10), timeout.Token) .ConfigureAwait(false)).ConfigureAwait(false); adding = null; diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.RoutingReservation.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.RoutingReservation.cs index c6ad05e7a8..9615b199b6 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.RoutingReservation.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.RoutingReservation.cs @@ -120,7 +120,7 @@ async Task BrowseAsync() [TestCase(false)] [TestCase(true)] - public async Task PreparedBatchRejectsNamespaceRoutingChangesBeforeDecisionAsync(bool register) + public async Task PreparedBatchKeepsConcurrentNamespaceRoutingChangesOfOtherManagersAsync(bool register) { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); LifecycleResult publicationResult2 = await CommitChangeAsync( @@ -148,22 +148,22 @@ public async Task PreparedBatchRejectsNamespaceRoutingChangesBeforeDecisionAsync } int decisions = 0; long revision = lifecycle.Revision; - await Assert.ThatAsync(() => prepared.CommitAsync(_ => + // The batch does not touch the survivor's namespace: it is rebased onto the changed routes and keeps them. + await prepared.CommitAsync(_ => { decisions++; return default; - }, timeout.Token).AsTask(), Throws.InstanceOf()).ConfigureAwait(false); - Assert.That(decisions, Is.Zero); - Assert.That(prepared.IsCommitted, Is.False); - Assert.That(GetBranchRegistrations(lifecycle).Count, Is.EqualTo(1)); + }, timeout.Token).ConfigureAwait(false); + Assert.That(decisions, Is.EqualTo(1)); + Assert.That(prepared.IsCommitted, Is.True); + Assert.That(GetBranchRegistrations(lifecycle).Count, Is.EqualTo(2)); NodeId root = new(kRootNodeId, (ushort)m_server.CurrentInstance.NamespaceUris.GetIndex(kModelNamespaceUri)); (_, IAsyncNodeManager? owner) = await master.GetManagerHandleAsync(root, timeout.Token) .ConfigureAwait(false); Assert.That(owner, register ? Is.SameAs(survivor.NodeManager) : Is.Null); - await prepared.DisposeAsync().ConfigureAwait(false); - Assert.That(lifecycle.Revision, Is.EqualTo(revision)); - Assert.That(m_server.CurrentInstance.NamespaceUris.GetIndex(kSecondModelNamespaceUri), Is.EqualTo(-1)); + Assert.That(lifecycle.Revision, Is.EqualTo(revision + 1)); + await AssertReadinessValueAsync(kSecondModelNamespaceUri, kSecondRegistrationValue).ConfigureAwait(false); master.RegisterNamespaceManager(kModelNamespaceUri, survivor.NodeManager); Assert.That(master.UnregisterNamespaceManager(kModelNamespaceUri, survivor.NodeManager), Is.True); master.RegisterNamespaceManager(kModelNamespaceUri, survivor.NodeManager); diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Writer.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Writer.cs index e5b639fc9b..98adf0fc8f 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Writer.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.Writer.cs @@ -34,7 +34,7 @@ public async Task WriterAdmitsConcurrentInvocationsAndRejectsStaleCaptureBeforeF .ConfigureAwait(false)) { Assert.That(invocation.IsCurrent, Is.False); - await Assert.ThrowsAsync(async () => + await Assert.ThrowsAsync(async () => await invocation.PrepareAsync([LifecycleChange.Add(factory)], timeout.Token).ConfigureAwait(false)) .ConfigureAwait(false); await using ILifecycleWriter peer = await lifecycle.CaptureChanges() @@ -131,7 +131,7 @@ await Assert.ThatAsync( () => invocation.PrepareAsync( [LifecycleChange.Replace( replaced.Registrations[0].Slot, rejectedFactory)], timeout.Token).AsTask(), - Throws.TypeOf()).ConfigureAwait(false); + Throws.TypeOf()).ConfigureAwait(false); using (Assert.EnterMultipleScope()) { Assert.That(invocation.IsCurrent, Is.False); diff --git a/tests/Opc.Ua.Types.Tests/Encoders/EncodeableFactorySnapshotTests.cs b/tests/Opc.Ua.Types.Tests/Encoders/EncodeableFactorySnapshotTests.cs index e83b6754e7..65e761d21d 100644 --- a/tests/Opc.Ua.Types.Tests/Encoders/EncodeableFactorySnapshotTests.cs +++ b/tests/Opc.Ua.Types.Tests/Encoders/EncodeableFactorySnapshotTests.cs @@ -522,5 +522,63 @@ private static IEnumeratedType CreateEnumeration() private const string kNamespace = "urn:opcfoundation.org:Tests:FactorySnapshots"; private static readonly ExpandedNodeId s_structureId = new(9001, kNamespace); private static readonly ExpandedNodeId s_enumId = new(9002, kNamespace); + + /// + /// A rebased merge adds the candidate's registrations onto a newer serving factory and reserves the + /// revision it merged onto. + /// + [Test] + public void RebasedMergeAddsCandidateRegistrationsOntoNewerServingFactory() + { + var factory = new EncodeableFactory(); + EncodeableFactory proposed = factory.CaptureSnapshot(out EncodeableFactory source, out long revision); + IEncodeableType candidate = CreateNamedStructure("Candidate"); + IEncodeableType serving = CreateNamedStructure("Serving"); + proposed.Builder.AddEncodeableType(s_structureId, candidate).Commit(); + factory.Builder.AddEncodeableType(s_otherStructureId, serving).Commit(); + + Assert.Throws(() => + factory.PrepareAdditiveMerge(proposed, source, revision, new NamespaceTable())); + EncodeableFactory merged = factory.PrepareAdditiveMerge( + proposed, source, revision, new NamespaceTable(), rebase: true, out long mergedRevision); + using (EncodeableFactory.Publication publication = factory.BeginPublication(source, mergedRevision)) + { + publication.Complete(merged); + } + + using (Assert.EnterMultipleScope()) + { + Assert.That(factory.TryGetEncodeableType(s_structureId, out IEncodeableType? added), Is.True); + Assert.That(added, Is.SameAs(candidate)); + Assert.That(factory.TryGetEncodeableType(s_otherStructureId, out IEncodeableType? kept), Is.True); + Assert.That(kept, Is.SameAs(serving)); + Assert.That(factory.TryGetType(serving.XmlName, out IType? keptName), Is.True); + Assert.That(keptName, Is.SameAs(serving)); + } + } + + /// + /// A rebased merge rejects a registration another publication made for the same key after the capture. + /// + [Test] + public void RebasedMergeRejectsOverlappingRegistration() + { + var factory = new EncodeableFactory(); + EncodeableFactory proposed = factory.CaptureSnapshot(out EncodeableFactory source, out long revision); + proposed.Builder.AddEncodeableType(s_structureId, CreateNamedStructure("Candidate")).Commit(); + factory.Builder.AddEncodeableType(s_structureId, CreateNamedStructure("Serving")).Commit(); + + Assert.Throws(() => factory.PrepareAdditiveMerge( + proposed, source, revision, new NamespaceTable(), rebase: true, out _)); + } + + private static IEncodeableType CreateNamedStructure(string name) + { + var type = new Mock(); + type.SetupGet(value => value.XmlName).Returns(new XmlQualifiedName(name, kNamespace)); + return type.Object; + } + + private static readonly ExpandedNodeId s_otherStructureId = new(9003, kNamespace); } } diff --git a/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs b/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs index 976961f346..0052bc6294 100644 --- a/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs +++ b/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs @@ -741,5 +741,114 @@ void Declare(NodeId owner) candidate.Add(node); } } + + /// + /// Verifies that a rebased merge adds the candidate's registrations onto a newer serving image. + /// + [Test] + public void RebasedMergeAddsCandidateRegistrationsOntoNewerServingTypes() + { + TypeTable proposed = m_typeTable.CaptureSnapshot(out TypeTable source, out long revision); + var serving = new NodeId(5000); + var candidate = new NodeId(6000); + proposed.AddSubtype(candidate, s_rootTypeId); + m_typeTable.AddSubtype(serving, s_rootTypeId); + + Assert.Throws(() => + m_typeTable.PrepareAdditiveMerge(proposed, source, revision)); + TypeTable merged = m_typeTable.PrepareAdditiveMerge( + proposed, source, revision, rebase: true, out long mergedRevision); + + using (Assert.EnterMultipleScope()) + { + Assert.That(merged.IsTypeOf(candidate, s_rootTypeId), Is.True); + Assert.That(merged.IsTypeOf(serving, s_rootTypeId), Is.True); + Assert.That(merged.IsTypeOf(s_grandchildTypeId, s_rootTypeId), Is.True); + Assert.That(mergedRevision, Is.Not.EqualTo(revision)); + Assert.That(m_typeTable.IsCurrentSnapshot(source, mergedRevision), Is.True); + Assert.That(m_typeTable.IsKnown(candidate), Is.False); + } + } + + /// + /// Verifies that a rebased merge does not bring back types removed after the capture. + /// + [Test] + public void RebasedMergeDoesNotRestoreTypesRemovedAfterCapture() + { + TypeTable proposed = m_typeTable.CaptureSnapshot(out TypeTable source, out long revision); + var candidate = new NodeId(6000); + proposed.AddSubtype(candidate, s_rootTypeId); + m_typeTable.Remove(s_grandchildTypeId); + + TypeTable merged = m_typeTable.PrepareAdditiveMerge(proposed, source, revision, rebase: true, out _); + + using (Assert.EnterMultipleScope()) + { + Assert.That(merged.IsKnown(s_grandchildTypeId), Is.False); + Assert.That(merged.IsKnown(candidate), Is.True); + } + } + + /// + /// Verifies that a re-registered type keeps the candidate's registration version after a rebase, so the + /// retirement of the replaced registration does not remove it. + /// + [Test] + public void RebasedMergeKeepsCandidateRegistrationVersionOfReregisteredType() + { + TypeTable proposed = m_typeTable.CaptureSnapshot(out TypeTable source, out long revision); + long replaced = m_typeTable.GetRegistrationVersion(s_grandchildTypeId); + proposed.AddSubtype(s_grandchildTypeId, s_childTypeId); + m_typeTable.AddSubtype(new NodeId(5000), s_rootTypeId); + + TypeTable merged = m_typeTable.PrepareAdditiveMerge(proposed, source, revision, rebase: true, out _); + + using (Assert.EnterMultipleScope()) + { + Assert.That(merged.GetRegistrationVersion(s_grandchildTypeId), + Is.EqualTo(proposed.GetRegistrationVersion(s_grandchildTypeId))); + Assert.That(merged.GetRegistrationVersion(s_grandchildTypeId), Is.Not.EqualTo(replaced)); + Assert.That(merged.IsTypeOf(s_grandchildTypeId, s_childTypeId), Is.True); + } + } + + /// + /// Verifies that a rebased merge rejects a type that another publication registered, replaced or removed + /// after the capture, and a supertype that disappeared. + /// + /// The serving change made after the capture. + [TestCase("SameNewType")] + [TestCase("ReregisteredType")] + [TestCase("RemovedType")] + [TestCase("RemovedSupertype")] + public void RebasedMergeRejectsOverlappingTypeChanges(string change) + { + TypeTable proposed = m_typeTable.CaptureSnapshot(out TypeTable source, out long revision); + var added = new NodeId(6000); + switch (change) + { + case "SameNewType": + proposed.AddSubtype(added, s_rootTypeId); + m_typeTable.AddSubtype(added, s_rootTypeId); + break; + case "ReregisteredType": + proposed.AddSubtype(s_grandchildTypeId, s_childTypeId); + m_typeTable.AddSubtype(s_grandchildTypeId, s_childTypeId); + break; + case "RemovedType": + proposed.AddSubtype(s_grandchildTypeId, s_childTypeId); + m_typeTable.Remove(s_grandchildTypeId); + break; + default: + proposed.AddSubtype(added, s_childTypeId); + m_typeTable.Remove(s_grandchildTypeId); + m_typeTable.Remove(s_childTypeId); + break; + } + + Assert.Throws(() => + m_typeTable.PrepareAdditiveMerge(proposed, source, revision, rebase: true, out _)); + } } } diff --git a/tests/Opc.Ua.Types.Tests/Utils/StringTablePrivateViewTests.cs b/tests/Opc.Ua.Types.Tests/Utils/StringTablePrivateViewTests.cs index 017d667c74..38708f5d54 100644 --- a/tests/Opc.Ua.Types.Tests/Utils/StringTablePrivateViewTests.cs +++ b/tests/Opc.Ua.Types.Tests/Utils/StringTablePrivateViewTests.cs @@ -397,6 +397,65 @@ public void MappingWithoutRemoteServerUrisLeavesEmptyDestinationUnchanged(bool l Assert.That(destination.Version, Is.EqualTo(version)); } + /// + /// A rebased publication without additions keeps the entries appended after preparation. + /// + /// Whether the table is a namespace table. + [TestCase(false)] + [TestCase(true)] + public void RebasedPublicationKeepsEntriesAppendedAfterPreparation(bool namespaces) + { + StringTable serving = CreateTable(namespaces); + StringTable staged = serving.CaptureSnapshot(); + long version = serving.Version; + serving.Append("urn:other"); + + Assert.Throws(() => serving.BeginPublication(staged, version)); + using (StringTable.Publication publication = serving.BeginPublication(staged, version, rebase: true)) + { + publication.Complete(); + } + Assert.That(serving.ToArray(), Is.EqualTo([Namespaces.OpcUa, "urn:base", "urn:other"])); + } + + /// + /// A rebased publication accepts entries appended meanwhile at the indexes it prepared, when they match. + /// + [Test] + public void RebasedPublicationAcceptsMatchingEntryAtPreparedIndex() + { + StringTable serving = CreateTable(namespaces: true); + StringTable staged = serving.CaptureSnapshot(); + staged.Append("urn:shared"); + staged.Append("urn:candidate"); + long version = serving.Version; + serving.Append("urn:shared"); + + using (StringTable.Publication publication = serving.BeginPublication(staged, version, rebase: true)) + { + publication.Complete(); + } + Assert.That(serving.ToArray(), + Is.EqualTo([Namespaces.OpcUa, "urn:base", "urn:shared", "urn:candidate"])); + } + + /// + /// A rebased publication rejects a different entry appended meanwhile at an index it prepared. + /// + [Test] + public void RebasedPublicationRejectsDifferentEntryAtPreparedIndex() + { + StringTable serving = CreateTable(namespaces: true); + StringTable staged = serving.CaptureSnapshot(); + staged.Append("urn:candidate"); + long version = serving.Version; + serving.Append("urn:other"); + + Assert.Throws(() => + serving.BeginPublication(staged, version, rebase: true)); + Assert.That(serving.ToArray(), Is.EqualTo([Namespaces.OpcUa, "urn:base", "urn:other"])); + } + private static StringTable CreateTable(bool namespaces) { return namespaces diff --git a/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs b/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs index 073c17554f..c45e8d039f 100644 --- a/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs +++ b/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs @@ -132,7 +132,7 @@ public async Task RealReferenceReservationsRetryWithinThePredecisionBudget(int c HandoffRequest("real-reference-conflict"), ct).ConfigureAwait(false)) .ConfigureAwait(false); Assert.That(failure!.GetType().FullName, - Is.EqualTo("Opc.Ua.OptimisticPublicationConflictException")); + Is.EqualTo("Opc.Ua.Server.NodeManagerLifecycleConflictException")); Assert.That(failure.Message, Is.EqualTo("Serving references changed during preparation.")); Assert.That(coordinator.Generation, Is.Zero); Assert.That(m_registry.Current, Is.SameAs(before)); From 99abcfcc9dd038d31184cfd69d32e34d13766482 Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Sat, 28 Nov 2026 13:49:02 +0100 Subject: [PATCH 2/5] Tests: expect the public lifecycle conflict for a stale prepared validation The retained-inspection validation test asserted the internal OptimisticPublicationConflictException; pre-decision metadata conflicts are now wrapped in NodeManagerLifecycleConflictException. Co-Authored-By: Claude Opus 5.5 --- .../NodeManager/PreparedNodeManagerTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/PreparedNodeManagerTests.cs b/tests/Opc.Ua.Server.Tests/NodeManager/PreparedNodeManagerTests.cs index 3fac408553..492c95e6f5 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/PreparedNodeManagerTests.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/PreparedNodeManagerTests.cs @@ -527,7 +527,8 @@ await Assert.ThrowsAsync(async () => await writer.Prepa } else { - Assert.That(observed, Is.TypeOf()); + Assert.That(observed, Is.TypeOf()); + Assert.That(observed!.InnerException, Is.TypeOf()); failure = observed!; } manager.Verify(value => value.DeleteAddressSpaceAsync(It.IsAny()), Times.Once); From 31e632c1ed4f6a008194564e9c32fd07c0dd5250 Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Sat, 28 Nov 2026 16:20:15 +0100 Subject: [PATCH 3/5] Server: tighten lifecycle rebase checks from review - Reject a rebase when a live NodeManager whose read image the batch replaces changed generation or serving image after preparation. - Report an OptimisticPublicationConflictException as the retryable lifecycle conflict only when the host found it before invoking the durable decision; exceptions from the decision callback pass through unchanged. - A rebased type registration whose supertype was removed meanwhile is a conflict even when the surviving type keeps its deleted ancestor pointer. Co-Authored-By: Claude Opus 5.5 --- .../Lifecycle/NodeManagerLifecycle.cs | 38 +++++++++++++++++-- src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs | 4 +- ...gerLifecycleTests.ConcurrentPreparation.cs | 20 ++++++++++ .../Nodes/TypeTableTests.Snapshots.cs | 6 +++ 4 files changed, 64 insertions(+), 4 deletions(-) diff --git a/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.cs b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.cs index 2cd443630e..da1ad53031 100644 --- a/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.cs +++ b/src/Opc.Ua.Server/NodeManager/Lifecycle/NodeManagerLifecycle.cs @@ -2273,6 +2273,30 @@ private void RebaseOrReject(PreparationPayload batch, string message) "A namespace or server URI index the batch assigned now identifies another URI.", batch.RoutingRevision); } + // A read image bound for a live generation outside the batch replaces that owner's serving image: the + // owner must still be the same generation with the same serving image, or a newer image would be lost. + foreach (INodeManagerReadImage image in batch.ReadImages) + { + if (image?.Owner is not { } owner || + batch.Entries.Exists(entry => ReferenceEquals(entry.Manager, owner))) + { + continue; + } + bool unchanged = + batch.RoutingRevision.TryGetGeneration(owner, out NodeManagerGeneration? prepared) && + serving.TryGetGeneration(owner, out NodeManagerGeneration? current) && + ReferenceEquals(prepared, current) && + ReferenceEquals( + batch.RoutingRevision.ReadImages.TryGetValue(owner, out INodeManagerReadImage? before) + ? before : null, + serving.ReadImages.TryGetValue(owner, out INodeManagerReadImage? after) ? after : null); + if (!unchanged) + { + throw new NodeManagerRoutingConflictException( + "A NodeManager whose read image the batch replaces changed after preparation.", + batch.RoutingRevision); + } + } batch.Rebase(serving); static bool IsPrefixConsistent(StringTable prepared, StringTable serving) @@ -2945,6 +2969,7 @@ public async ValueTask DecideAsync( throw new InvalidOperationException("A validation unit cannot publish."); } m_batch.Publication?.ValidateRevision(m_batch.Server); + m_batch.DecisionStarted = true; if (m_decideAsync is not null) { await m_mutation.DecideAsync(m_decideAsync, reservation, cancellationToken) @@ -3714,6 +3739,12 @@ public PreparationPayload( /// public bool DecisionCommitted { get; set; } + /// + /// Gets or sets whether the durable decision callback was invoked. Only conflicts the host detects + /// before this point are reported as a retryable . + /// + public bool DecisionStarted { get; set; } + /// /// Gets the sole worker allowed to commit this replacement. /// @@ -4163,10 +4194,11 @@ private async Task CompleteAsync( } catch (Exception failure) when (failure is not OutOfMemoryException) { - // A stale type, factory, namespace or reference image found before the decision is the - // same retryable conflict as a stale routing view. + // A stale type, factory, namespace or reference image the host found before invoking the + // decision is the same retryable conflict as a stale routing view. Exceptions from the + // decision callback itself pass through unchanged. executionFailure = failure is OptimisticPublicationConflictException && - !payload.DecisionCommitted && !payload.IsCommitted + !payload.DecisionStarted && !payload.IsCommitted ? new NodeManagerLifecycleConflictException(failure.Message, failure) : failure; } diff --git a/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs b/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs index d4645afc2d..86112b9d1c 100644 --- a/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs +++ b/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs @@ -260,7 +260,9 @@ additions.m_captureSource is null || { if (!merged.m_nodes.TryGetValue(parent.NodeId, out TypeInfo? superType)) { - if (target.SuperType?.NodeId == parent.NodeId) + // An unchanged capture may keep a deleted ancestor; a rebased registration may not, because + // its supertype was removed after the batch saw it. + if (only is null && target.SuperType?.NodeId == parent.NodeId) { continue; } diff --git a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ConcurrentPreparation.cs b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ConcurrentPreparation.cs index 8b2a1736dc..76568a10f2 100644 --- a/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ConcurrentPreparation.cs +++ b/tests/Opc.Ua.Server.Tests/NodeManager/NodeManagerLifecycleTests.ConcurrentPreparation.cs @@ -193,6 +193,26 @@ async Task ReloadAsync(NodeManagerSlot slot, string namespaceUri, int baseValue) } } + /// + /// A conflict raised by the durable decision callback itself is not reported as the host's retryable + /// conflict: the callback already ran, so it reaches the caller unchanged. + /// + [Test] + public async Task DecisionCallbackConflictIsNotReportedAsRetryableAsync() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + INodeManagerLifecycle lifecycle = m_server.NodeManagerLifecycle; + await using IPreparedChanges prepared = await lifecycle.PrepareAsync( + [LifecycleChange.Add(RuntimeFactory(kModelNamespaceUri, kFirstRegistrationValue))], timeout.Token) + .ConfigureAwait(false); + var failure = new OptimisticPublicationConflictException("Raised by the decision callback."); + + await Assert.ThatAsync( + async () => await prepared.CommitAsync(_ => throw failure, timeout.Token).ConfigureAwait(false), + Throws.Exception.SameAs(failure)).ConfigureAwait(false); + Assert.That(prepared.IsCommitted, Is.False); + } + private static RuntimeNodeSetNodeManagerFactory RuntimeFactory(string namespaceUri, int value) { return new RuntimeNodeSetNodeManagerFactory(CreateOptions(namespaceUri, value)); diff --git a/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs b/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs index 0052bc6294..9123ef692f 100644 --- a/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs +++ b/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs @@ -822,6 +822,7 @@ public void RebasedMergeKeepsCandidateRegistrationVersionOfReregisteredType() [TestCase("ReregisteredType")] [TestCase("RemovedType")] [TestCase("RemovedSupertype")] + [TestCase("RemovedSupertypeOfReregisteredType")] public void RebasedMergeRejectsOverlappingTypeChanges(string change) { TypeTable proposed = m_typeTable.CaptureSnapshot(out TypeTable source, out long revision); @@ -840,6 +841,11 @@ public void RebasedMergeRejectsOverlappingTypeChanges(string change) proposed.AddSubtype(s_grandchildTypeId, s_childTypeId); m_typeTable.Remove(s_grandchildTypeId); break; + case "RemovedSupertypeOfReregisteredType": + // The surviving child keeps its deleted parent pointer; its re-registration must still conflict. + proposed.AddSubtype(s_grandchildTypeId, s_childTypeId); + m_typeTable.Remove(s_childTypeId); + break; default: proposed.AddSubtype(added, s_childTypeId); m_typeTable.Remove(s_grandchildTypeId); From 68c2b769a0512fcffc05ce7158d254cee7622ec4 Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Sat, 28 Nov 2026 17:21:43 +0100 Subject: [PATCH 4/5] Types: close two rebase gaps in factory and type-table merges - A rebased encodeable merge also checks the XML names used by every added or replaced registration, so an alias for an existing type is rejected when another publication remapped that type's XML name. - A type the candidate removes and re-adds keeps its captured serving version, so an unrelated publication does not make the batch stale. Co-Authored-By: Claude Opus 5.5 --- .../Encoders/EncodeableFactory.Snapshots.cs | 9 +++++++- src/Opc.Ua.Types/Nodes/TypeTable.cs | 2 ++ .../EncodeableFactorySnapshotTests.cs | 19 +++++++++++++++ .../Nodes/TypeTableTests.Snapshots.cs | 23 +++++++++++++++++++ 4 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/Opc.Ua.Types/Encoders/EncodeableFactory.Snapshots.cs b/src/Opc.Ua.Types/Encoders/EncodeableFactory.Snapshots.cs index 9a40af5ca6..064b510b96 100644 --- a/src/Opc.Ua.Types/Encoders/EncodeableFactory.Snapshots.cs +++ b/src/Opc.Ua.Types/Encoders/EncodeableFactory.Snapshots.cs @@ -150,7 +150,14 @@ internal EncodeableFactory PrepareAdditiveMerge( $"Registration '{key}' changed after the batch was prepared."); } } - foreach (XmlQualifiedName key in proposed.m_xmlNameToType.Keys) + // An added alias for an existing type shares that type's XML name without changing the XML-name + // entry, so every XML name an added or replaced registration uses must also be unchanged. + IEnumerable xmlNames = proposed.m_xmlNameToType.Keys + .Concat(proposed.m_encodeableTypes.Values.Select(type => type.XmlName)) + .Concat(proposed.m_enumeratedTypes.Values.Select(type => type.XmlName)) + .Where(name => name is not null) + .Distinct(); + foreach (XmlQualifiedName key in xmlNames) { if (!CapturedMaps.IsUnchanged(captured.XmlNames, merged.m_xmlNameToType, key)) { diff --git a/src/Opc.Ua.Types/Nodes/TypeTable.cs b/src/Opc.Ua.Types/Nodes/TypeTable.cs index 5042bc8028..4b002f5b8f 100644 --- a/src/Opc.Ua.Types/Nodes/TypeTable.cs +++ b/src/Opc.Ua.Types/Nodes/TypeTable.cs @@ -877,6 +877,8 @@ internal bool TryRemoveRegistration(NodeId typeId, long registrationVersion) /// private void RemoveRegistration(NodeId typeId) { + // Keeps the captured serving version when a candidate removes and later re-adds a type. + TrackStagedRegistration(typeId); EnsureWritableGraph(); TypeInfo typeInfo = m_nodes[typeId]; m_revision++; diff --git a/tests/Opc.Ua.Types.Tests/Encoders/EncodeableFactorySnapshotTests.cs b/tests/Opc.Ua.Types.Tests/Encoders/EncodeableFactorySnapshotTests.cs index 65e761d21d..dc4367f080 100644 --- a/tests/Opc.Ua.Types.Tests/Encoders/EncodeableFactorySnapshotTests.cs +++ b/tests/Opc.Ua.Types.Tests/Encoders/EncodeableFactorySnapshotTests.cs @@ -572,6 +572,25 @@ public void RebasedMergeRejectsOverlappingRegistration() proposed, source, revision, new NamespaceTable(), rebase: true, out _)); } + /// + /// A rebased merge rejects an alias the candidate added for an existing type when another publication + /// remapped that type's XML name, so encoding and XML-name lookups cannot resolve to different types. + /// + [Test] + public void RebasedMergeRejectsAliasWhoseXmlNameWasRemapped() + { + var factory = new EncodeableFactory(); + IEncodeableType original = CreateNamedStructure("Shared"); + factory.Builder.AddEncodeableType(s_structureId, original).Commit(); + EncodeableFactory proposed = factory.CaptureSnapshot(out EncodeableFactory source, out long revision); + proposed.Builder.AddEncodeableType(s_otherStructureId, original).Commit(); + factory.Builder.AddEncodeableType(new ExpandedNodeId(9004, kNamespace), CreateNamedStructure("Shared")) + .Commit(); + + Assert.Throws(() => factory.PrepareAdditiveMerge( + proposed, source, revision, new NamespaceTable(), rebase: true, out _)); + } + private static IEncodeableType CreateNamedStructure(string name) { var type = new Mock(); diff --git a/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs b/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs index 9123ef692f..512491294d 100644 --- a/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs +++ b/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs @@ -813,6 +813,29 @@ public void RebasedMergeKeepsCandidateRegistrationVersionOfReregisteredType() } } + /// + /// Verifies that a type the candidate removed and re-added privately keeps its captured serving version, so + /// an unrelated publication does not make the batch stale. + /// + [Test] + public void RebasedMergeAcceptsTypeRemovedAndReaddedByCandidate() + { + TypeTable proposed = m_typeTable.CaptureSnapshot(out TypeTable source, out long revision); + proposed.Remove(s_grandchildTypeId); + proposed.AddSubtype(s_grandchildTypeId, s_childTypeId); + m_typeTable.AddSubtype(new NodeId(5000), s_rootTypeId); + + TypeTable merged = m_typeTable.PrepareAdditiveMerge(proposed, source, revision, rebase: true, out _); + + using (Assert.EnterMultipleScope()) + { + Assert.That(merged.IsTypeOf(s_grandchildTypeId, s_childTypeId), Is.True); + Assert.That(merged.GetRegistrationVersion(s_grandchildTypeId), + Is.EqualTo(proposed.GetRegistrationVersion(s_grandchildTypeId))); + Assert.That(merged.IsKnown(new NodeId(5000)), Is.True); + } + } + /// /// Verifies that a rebased merge rejects a type that another publication registered, replaced or removed /// after the capture, and a supertype that disappeared. From 7695578ee737d2257cb37923c729d86099ffe541 Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Sat, 28 Nov 2026 18:14:09 +0100 Subject: [PATCH 5/5] Types: report concurrent encoding ownership changes as rebase conflicts In a rebased type merge, an encoding that another publication assigned to a different type, or whose data type disappeared, is now an OptimisticPublicationConflictException (surfaced as the retryable lifecycle conflict) instead of a plain InvalidOperationException. Co-Authored-By: Claude Opus 5.5 --- src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs | 14 ++++++++++---- .../Nodes/TypeTableTests.Snapshots.cs | 6 ++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs b/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs index 86112b9d1c..be2ea0a4f8 100644 --- a/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs +++ b/src/Opc.Ua.Types/Nodes/TypeTable.Snapshots.cs @@ -314,16 +314,22 @@ additions.m_captureSource is null || { continue; } + // Staging already rejects a candidate that takes over an encoding owned at capture, so in a rebase + // a mismatch here was introduced by another publication after the batch was prepared. if (!merged.m_nodes.TryGetValue(encoding.Value.NodeId, out TypeInfo? target)) { - throw new InvalidOperationException( - $"Encoding '{encoding.Key}' requires an unavailable data type."); + string unavailable = $"Encoding '{encoding.Key}' requires an unavailable data type."; + throw only is not null + ? new OptimisticPublicationConflictException(unavailable) + : new InvalidOperationException(unavailable); } if (merged.m_encodings.TryGetValue(encoding.Key, out TypeInfo? existing) && existing.NodeId != target.NodeId) { - throw new InvalidOperationException( - $"Encoding '{encoding.Key}' cannot redefine a serving data type."); + string redefined = $"Encoding '{encoding.Key}' cannot redefine a serving data type."; + throw only is not null + ? new OptimisticPublicationConflictException(redefined) + : new InvalidOperationException(redefined); } merged.m_encodings[encoding.Key] = target; if (target.Encodings is null) diff --git a/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs b/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs index 512491294d..dc9da658cc 100644 --- a/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs +++ b/tests/Opc.Ua.Types.Tests/Nodes/TypeTableTests.Snapshots.cs @@ -846,6 +846,7 @@ public void RebasedMergeAcceptsTypeRemovedAndReaddedByCandidate() [TestCase("RemovedType")] [TestCase("RemovedSupertype")] [TestCase("RemovedSupertypeOfReregisteredType")] + [TestCase("SameNewEncodingForDifferentTypes")] public void RebasedMergeRejectsOverlappingTypeChanges(string change) { TypeTable proposed = m_typeTable.CaptureSnapshot(out TypeTable source, out long revision); @@ -864,6 +865,11 @@ public void RebasedMergeRejectsOverlappingTypeChanges(string change) proposed.AddSubtype(s_grandchildTypeId, s_childTypeId); m_typeTable.Remove(s_grandchildTypeId); break; + case "SameNewEncodingForDifferentTypes": + // Both assign a previously unused encoding to different, otherwise unchanged types. + Assert.That(proposed.AddEncoding(s_childTypeId, new ExpandedNodeId(7001)), Is.True); + Assert.That(m_typeTable.AddEncoding(s_grandchildTypeId, new ExpandedNodeId(7001)), Is.True); + break; case "RemovedSupertypeOfReregisteredType": // The surviving child keeps its deleted parent pointer; its re-registration must still conflict. proposed.AddSubtype(s_grandchildTypeId, s_childTypeId);