Files
UA-.NETStandard/tests/Opc.Ua.OpenUsd.Tests/ConnectionFidelityTests.cs
Marc Schier da7412c429 Add native xRegistry events and distinct Resource versions (#4396)
## Summary

- support the xRegistry 0.6.0 distinct Resource/Version hierarchy:
  `Registry -> Group -> Resource -> Versions -> Version`
- instantiate stable logical Resource nodes separately from exact
Version nodes
  while preserving existing Version NodeIds
- delegate logical Resource FileType operations and Version-view
metadata to the
selected default Version with handle pinning and shared writer
reservations
- make Resource and Version delete behavior role-stable and use
`MetaEpoch` /
  `Epoch` respectively
- use stable Resource SourceNodes, exact Version SourceNodes and the
  `Server -> Registry -> Group -> Resource -> Version` notifier chain
- keep a model-metadata-gated client fallback for 0.5 flat Servers; 0.6
Servers
  expose no legacy aliases
- target `HasWoTProjection` at the real stable logical Resource node
- use `AsyncCustomNodeManager` for the registration, fast-path, and
federation managers,
  with awaited lifecycle, node mutations, event delivery, and cleanup
- handle startup rollback, reentrant deletion callbacks, undisclosed
file handles,
  and retryable cleanup without blocking unrelated file operations

## Authoritative dependencies

- companion specification: OPCF-Members/spec-drafts#32 at
  `d3399fca025025a73e5a6b599f850a81d985c060`
- OPC UA binding: xregistry/spec#568
- xRegistry event semantics: xregistry/spec#563, merged as
  `66ee31e47fbadff6ab982ae1516f7d9065e46b64`
- companion NodeSet SHA-256:
  `369f5f3f1814b333e4eeb52bfb4b6a730cdff372505a5f91a54c94f0016ac4cf`

## Review feedback

- keep the WoT Connectivity information-model designation at `1.1`;
draft revisions update the publication date without changing the model
version
- eliminate all 198 unique CA1861 diagnostics across 54 files and remove
seven obsolete project suppressions
- fix the analyzer-clean touched-path CA1307 and the hierarchy follow-up
CA1846/CA1851 diagnostics without dropping legacy-TFM compatibility

- recover the reconcile queue after callback faults/cancellation and
continue accepted pending changes
- remove migration guidance for the xRegistry managers, which are new in
2.0

## Compatibility

- public WoT Connectivity model designation remains `1.1`
- generated event-record ABI, constructors, options, NodeIds, and stored
documents remain compatible
- the generic xRegistry managers are new in 2.0 and implement
`IAsyncNodeManager`;
use `IAsyncNodeManagerFactory` and the async lifecycle hooks (see
`docs\XRegistry.md`)
- persistence schema and document blobs remain compatible unless noted
below

## Validation

- merge validation at `980422f76` with upstream `e8bec27d5`: 454
targeted WoT/materialization/model/registry cases and all 327 XRegistry
cases passed on both net10.0 and net48; all 29 net10 aggregation sample
cases passed
- feedback regressions at `308e8ba74`: 55 targeted queue and live
registry event/projection/lifecycle cases passed on each of net10.0 and
net48
- prior CI: all 266 checks passed at `6489a0908`; the unchanged Ubuntu
Core certificate-counter test and dependent jobs passed on the one-time
retry ([run 34117304035, attempt
2](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/34117304035/attempts/2))
- `Opc.Ua.XRegistry.Tests` — 327 passed on net10.0 and net48 for
migration commit `32c914aaf`
- `Opc.Ua.WotCon.Tests` net10.0 — 1348 passed
- `Opc.Ua.WotCon.Bindings.Tests` net10.0 — 683 passed
- `Opc.Ua.SourceGeneration.Core.Tests` net10.0 — 3807 passed, 8 skipped
- `Opc.Ua.SourceGeneration.Tests` net10.0 — 145 passed
- `Opc.Ua.SourceGeneration.Stack.Tests` net10.0 — 94 passed
- affected XRegistry and WoT client/server projects build successfully
- xRegistry NodeSet is byte-identical to the companion artifact
- repository-wide CA1861 inventory — 198 unique diagnostics across 54
files reduced to zero
- targeted changed-fixture validation — 1,098 passed, 3 skipped, 0
failed
- constrained full `UA.slnx` net10.0 Release build — CA1861 = 0
- `Opc.Ua.XRegistry.Client` net472 and netstandard2.1 builds — 0
warnings, 0 errors
- independent shared-array safety review — no significant issues
- `git diff --check`

The final review regressions cover concurrent reconcile/open, synthetic
logical
handle collisions across default switches, cross-session Close
isolation,
shared writer reservations, logical FileType property/change
propagation,
logical Labels delegation, role-fixed deletion, event sources,
model-version
gating, and stable `HasWoTProjection` targets.

The companion specification and protocol binding are reviewed in the
linked PRs above.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5c79a1ed-6dab-4522-a9fc-6548caa78ad5
Copilot-Session: b605797f-a97a-4cd0-8f12-016d33c2fd88
Copilot-Session: 7ef369a5-2307-4f71-8a11-15af0e72f240
Copilot-Session: e716d455-8397-4d22-9c5a-398847ab7317
2026-09-08 04:46:40 +00:00

242 lines
12 KiB
C#

/* ========================================================================
* 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/
* ======================================================================*/
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Opc.Ua.OpenUsd.Scene;
using Opc.Ua.OpenUsd.Server.Scene;
namespace Opc.Ua.OpenUsd.Tests
{
/// <summary>
/// Attribute-connection fidelity across materialize→export (§5.4, §7.4):
/// <list type="bullet">
/// <item>M-2 — the exported connection sequence equals the authored order, recovered from
/// the materialization result's side channel rather than from hash-ordered references.</item>
/// <item>M-5 — a <c>.connect</c> whose target lies outside the materialized subtree (and so
/// has no browsable edge) still survives the round trip, the connection counterpart of a
/// relationship's <c>TargetPaths</c>.</item>
/// <item>M-4 — an attribute co-authored with both a default value and a connection reports
/// both after export; neither is discarded.</item>
/// </list>
/// </summary>
[TestFixture]
public class ConnectionFidelityTests
{
// ---- M-2: exported connection order equals authored order ----------------------
[Test]
public void Export_TwoConnections_PreservesAuthoredOrder()
{
// Author the two targets in reverse-alphabetical order so authored order (b, a) is
// distinguishable from any incidental sort or hash order (which would give a, b).
var stage = new UsdStage("S") { DefaultPrim = "Sink" };
var src = new UsdPrim("Src", "Xform");
src.Attributes.Add(new UsdAttribute("a", "double") { Value = UsdValue.From(1.0) });
src.Attributes.Add(new UsdAttribute("b", "double") { Value = UsdValue.From(2.0) });
var sink = new UsdPrim("Sink", "Xform");
var input = new UsdAttribute("in", "double");
input.Connections.Add("/Src.b");
input.Connections.Add("/Src.a");
sink.Attributes.Add(input);
stage.AddRootPrim(src);
stage.AddRootPrim(sink);
MaterializedScene ms = MaterializationHarness.Materialize(stage);
// The result overload carries the recorded authored order (M-2 fix).
UsdStage exported = ms.Context.ExportUsdStage(ms.Result);
UsdAttribute exportedInput = AttributeOf(exported, "Sink", "in");
Assert.That(exportedInput.Connections, Is.EqualTo(s_stringValues1),
"Exported connections must be in the authored order, not reference/hash order.");
}
[Test]
public void Materialize_RecordsAuthoredConnectionOrder_OnResult()
{
// The mechanism that makes M-2/M-5 deterministic: the authored connection paths are
// snapshotted verbatim onto the materialization result, keyed by attribute node.
var stage = new UsdStage("S") { DefaultPrim = "Sink" };
var src = new UsdPrim("Src", "Xform");
src.Attributes.Add(new UsdAttribute("a", "double") { Value = UsdValue.From(1.0) });
src.Attributes.Add(new UsdAttribute("b", "double") { Value = UsdValue.From(2.0) });
var sink = new UsdPrim("Sink", "Xform");
var input = new UsdAttribute("in", "double");
input.Connections.Add("/Src.b");
input.Connections.Add("/Src.a");
sink.Attributes.Add(input);
stage.AddRootPrim(src);
stage.AddRootPrim(sink);
MaterializedScene ms = MaterializationHarness.Materialize(stage);
UsdAttributeState node = ms.Attr("/Sink.in");
Assert.That(ms.Result.ConnectionsByNode.ContainsKey(node), Is.True,
"A connected attribute must be recorded on the result.");
Assert.That(ms.Result.ConnectionsByNode[node],
Is.EqualTo(s_stringValues1),
"The recorded order must be the authored order.");
}
[Test]
public void Materialize_TwoConnectionsFromOneAttribute_DoesNotThrow()
{
// Regression guard: materialized attributes share the model's placeholder NodeId
// (xUsdAttribute_, i=6023), so two connections authored on one attribute resolve to
// the same target NodeId. The browsable-edge builder must dedupe by target NodeId
// rather than throwing a duplicate-reference exception. The lossless authored order is
// preserved separately on the result (asserted by the tests above).
var stage = new UsdStage("S") { DefaultPrim = "Sink" };
var src = new UsdPrim("Src", "Xform");
src.Attributes.Add(new UsdAttribute("a", "double") { Value = UsdValue.From(1.0) });
src.Attributes.Add(new UsdAttribute("b", "double") { Value = UsdValue.From(2.0) });
var sink = new UsdPrim("Sink", "Xform");
var input = new UsdAttribute("in", "double");
input.Connections.Add("/Src.b");
input.Connections.Add("/Src.a");
sink.Attributes.Add(input);
stage.AddRootPrim(src);
stage.AddRootPrim(sink);
MaterializedScene ms = null!;
Assert.DoesNotThrow(
() => ms = MaterializationHarness.Materialize(stage),
"Two resolvable connections sharing a target NodeId must not throw.");
Assert.That(ms.Result.ConnectionsByNode[ms.Attr("/Sink.in")],
Is.EqualTo(s_stringValues1),
"Both authored connections must still be recorded despite the deduped edge.");
}
[Test]
public void Export_UnresolvableConnectionTarget_Survives()
{
// The target lies outside the materialized subtree, so no browsable UsdConnection edge
// exists for it. The recorded authored path is the only way it can round-trip.
var stage = new UsdStage("S") { DefaultPrim = "Sink" };
var sink = new UsdPrim("Sink", "Xform");
var input = new UsdAttribute("in", "double");
input.Connections.Add("/Outside/Elsewhere.output");
sink.Attributes.Add(input);
stage.AddRootPrim(sink);
MaterializedScene ms = MaterializationHarness.Materialize(stage);
UsdStage exported = ms.Context.ExportUsdStage(ms.Result);
UsdAttribute exportedInput = AttributeOf(exported, "Sink", "in");
Assert.That(exportedInput.Connections,
Is.EqualTo(s_stringValues2),
"An unresolvable .connect target must not be dropped (§8.4 shall-not-drop).");
}
[Test]
public void Export_MixedResolvableAndUnresolvable_PreservesBothInOrder()
{
// One target resolves inside the subtree, one does not; both must appear, in the exact
// authored order, proving the side channel — not the edges — drives the export.
var stage = new UsdStage("S") { DefaultPrim = "Sink" };
var src = new UsdPrim("Src", "Xform");
src.Attributes.Add(new UsdAttribute("out", "double") { Value = UsdValue.From(1.0) });
var sink = new UsdPrim("Sink", "Xform");
var input = new UsdAttribute("in", "double");
input.Connections.Add("/Missing.target");
input.Connections.Add("/Src.out");
sink.Attributes.Add(input);
stage.AddRootPrim(src);
stage.AddRootPrim(sink);
MaterializedScene ms = MaterializationHarness.Materialize(stage);
UsdStage exported = ms.Context.ExportUsdStage(ms.Result);
UsdAttribute exportedInput = AttributeOf(exported, "Sink", "in");
Assert.That(exportedInput.Connections,
Is.EqualTo(s_stringValues3),
"Both the unresolvable and the resolvable target must survive, in authored order.");
}
// ---- M-4: a value co-authored with a connection is not discarded ---------------
[Test]
public void Export_AttributeWithValueAndConnection_ReportsBoth()
{
// USD permits an attribute to carry both a default value and a connection; the
// materializer must keep the value while the connection is recorded, and the exporter
// must report both independently (§5.4, §7.2).
var stage = new UsdStage("S") { DefaultPrim = "Sink" };
var src = new UsdPrim("Src", "Xform");
src.Attributes.Add(new UsdAttribute("out", "double") { Value = UsdValue.From(3.0) });
var sink = new UsdPrim("Sink", "Xform");
var input = new UsdAttribute("in", "double") { Value = UsdValue.From(1.5) };
input.Connections.Add("/Src.out");
sink.Attributes.Add(input);
stage.AddRootPrim(src);
stage.AddRootPrim(sink);
MaterializedScene ms = MaterializationHarness.Materialize(stage);
// The materialized node keeps its default value even though it is connected.
Assert.That(ms.Attr("/Sink.in").BoxedValue(), Is.EqualTo(1.5),
"The materializer must not discard the value when a connection is present.");
UsdStage exported = ms.Context.ExportUsdStage(ms.Result);
UsdAttribute exportedInput = AttributeOf(exported, "Sink", "in");
UsdTestHelpers.AssertDouble(exportedInput.Value, 1.5);
Assert.That(exportedInput.Value.IsNull, Is.False,
"The exported attribute must still report its default value.");
Assert.That(exportedInput.Connections, Is.EqualTo(s_stringValues4),
"The exported attribute must also report its connection.");
}
private static UsdAttribute AttributeOf(UsdStage stage, string primName, string attributeName)
{
foreach (UsdPrim prim in stage.RootPrims)
{
if (!string.Equals(prim.Name, primName, StringComparison.Ordinal))
{
continue;
}
foreach (UsdAttribute attribute in prim.Attributes)
{
if (string.Equals(attribute.Name, attributeName, StringComparison.Ordinal))
{
return attribute;
}
}
}
Assert.Fail($"Attribute {primName}.{attributeName} was not found in the exported stage.");
return new UsdAttribute(attributeName, string.Empty);
}
private static readonly string[] s_stringValues1 = ["/Src.b", "/Src.a"];
private static readonly string[] s_stringValues2 = ["/Outside/Elsewhere.output"];
private static readonly string[] s_stringValues3 = ["/Missing.target", "/Src.out"];
private static readonly string[] s_stringValues4 = ["/Src.out"];
}
}