test(config): #1049 real-DB DanglingReference race + snapshot isolation; NodeEdit/ClusterEdit stale-token and delete against SQL Server

DanglingReferenceSqlServerTests: the review's emptiness-check/add/delete race interleaved on two
real connections commits both and the deploy snapshot names the orphan; a consistent device+tag
commit landing mid-read (after Devices, before Tags) is invisible under the factory's SNAPSHOT
transaction, while the same interleave read READ COMMITTED produces exactly the false
DanglingReference (positive control).

ClusterNodeEditConcurrencySqlServerTests (bUnit on the AdminUI SQL fixture — InMemory generates no
rowversion and has no FKs): stale-token saves on NodeEdit/ClusterEdit are refused and the other
user's edit survives, current-token saves succeed, a deployed node deletes with its
NodeDeploymentState rows, a cluster with nodes is not deleted and the page says why.
This commit is contained in:
Joseph Doherty
2026-12-03 15:18:16 -05:00
parent 90de55535d
commit 49213e52e4
2 changed files with 367 additions and 0 deletions
@@ -0,0 +1,165 @@
using System.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// lmxopcua#1049 (#998 C-10 follow-up) on the real provider. The raw-tree parent links are LOGICAL foreign keys,
/// so the race the review described — user A's "is the device empty?" check passes, user B adds a tag under it,
/// A deletes the device — really commits both on SQL Server, and the deploy gate's <c>DanglingReference</c> rule is
/// what names the orphan. And because the deploy reads its whole snapshot under SNAPSHOT isolation, a
/// concurrent, perfectly consistent commit landing MID-read cannot make the gate report a dangling row that never
/// existed in any committed state (a parent read before the commit, its child read after it).
/// </summary>
[Trait("Category", "SchemaCompliance")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class DanglingReferenceSqlServerTests
{
private readonly SchemaComplianceFixture _fixture;
/// <summary>Initializes a new instance of the <see cref="DanglingReferenceSqlServerTests"/> class.</summary>
/// <param name="fixture">The migrated test database.</param>
public DanglingReferenceSqlServerTests(SchemaComplianceFixture fixture) => _fixture = fixture;
private OtOpcUaConfigDbContext NewContext(params IInterceptor[] interceptors) => new(
new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(_fixture.ConnectionString)
.AddInterceptors(interceptors).Options);
private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}";
private static Tag NewTag(string tagId, string deviceId) => new()
{
TagId = tagId, DeviceId = deviceId, Name = tagId, DataType = "Int32", AccessLevel = TagAccessLevel.Read, TagConfig = "{}",
};
/// <summary>Seeds cluster → driver → device; returns (driverId, deviceId).</summary>
private (string DriverId, string DeviceId) SeedDevice()
{
var clusterId = Id("cl")[..30];
var driverId = Id("di");
var deviceId = Id("dev");
using var db = NewContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "dev", NodeCount = 1,
RedundancyMode = RedundancyMode.None, CreatedBy = "t1049",
});
db.DriverInstances.Add(new DriverInstance
{
DriverInstanceId = driverId, ClusterId = clusterId, Name = Id("drv"), DriverType = "Modbus", DriverConfig = "{}",
});
db.Devices.Add(new Device { DeviceId = deviceId, DriverInstanceId = driverId, Name = Id("plc"), DeviceConfig = "{}" });
db.SaveChanges();
return (driverId, deviceId);
}
private static IEnumerable<ValidationError> DanglingFor(DraftSnapshot draft, string tagId) =>
DraftValidator.Validate(draft).Where(e => e.Code == DraftValidator.DanglingReferenceCode && e.Context == tagId);
/// <summary>
/// The review's race, interleaved on two real connections: A's emptiness check, B's tag add, A's device delete.
/// Both commit (no FK); the deploy snapshot then names the orphaned tag.
/// </summary>
[Fact]
public async Task A_device_deleted_while_a_tag_is_added_under_it_is_reported_by_the_deploy_gate()
{
var ct = TestContext.Current.CancellationToken;
var (_, deviceId) = SeedDevice();
var tagId = Id("tag");
await using (var userA = NewContext())
{
await using var tx = await userA.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
(await userA.Tags.AnyAsync(t => t.DeviceId == deviceId, ct)).ShouldBeFalse(); // "the device is empty"
await using (var userB = NewContext())
{
userB.Tags.Add(NewTag(tagId, deviceId));
await userB.SaveChangesAsync(ct); // commits while A's check result is already stale
}
userA.Devices.Remove(await userA.Devices.SingleAsync(d => d.DeviceId == deviceId, ct));
await userA.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
}
await using var deploy = NewContext();
var draft = await DraftSnapshotFactory.FromConfigDbAsync(deploy, ct);
draft.Tags.ShouldContain(t => t.TagId == tagId);
draft.Devices.ShouldNotContain(d => d.DeviceId == deviceId);
DanglingFor(draft, tagId).ShouldHaveSingleItem().Message.ShouldContain($"Device '{deviceId}'");
}
/// <summary>
/// A device and its tag added together in ONE commit that lands after the snapshot read has passed the Devices
/// table but before it reads Tags: under the factory's SNAPSHOT transaction neither is seen, so no false
/// <c>DanglingReference</c>. Positive control: the same interleave inside a READ COMMITTED transaction (the
/// factory then reads in the caller's transaction) DOES report the tag as dangling — so the isolation, not the
/// timing, is what keeps the gate honest; and a read after the commit sees both rows and no error.
/// </summary>
[Fact]
public async Task A_consistent_commit_landing_mid_read_is_never_reported_as_dangling_under_snapshot_isolation()
{
var ct = TestContext.Current.CancellationToken;
var (driverId, deviceId) = SeedDevice();
// Snapshot read (the deploy path): the concurrent commit is invisible.
var (lateDevice, lateTag) = (Id("dev"), Id("tag"));
await using (var db = NewContext(new CommitDeviceAndTagWhenDeviceMaterialises(_fixture.ConnectionString, deviceId, driverId, lateDevice, lateTag)))
{
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
draft.Tags.ShouldNotContain(t => t.TagId == lateTag);
DanglingFor(draft, lateTag).ShouldBeEmpty();
}
// Positive control 1: the same interleave read unisolated produces exactly the false positive.
var (lateDevice2, lateTag2) = (Id("dev"), Id("tag"));
await using (var db = NewContext(new CommitDeviceAndTagWhenDeviceMaterialises(_fixture.ConnectionString, deviceId, driverId, lateDevice2, lateTag2)))
{
await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
draft.Tags.ShouldContain(t => t.TagId == lateTag2);
DanglingFor(draft, lateTag2).ShouldHaveSingleItem();
}
// Positive control 2: both commits really landed, and a read started afterwards sees them whole.
await using var after = NewContext();
var later = await DraftSnapshotFactory.FromConfigDbAsync(after, ct);
later.Tags.ShouldContain(t => t.TagId == lateTag);
later.Devices.ShouldContain(d => d.DeviceId == lateDevice);
DanglingFor(later, lateTag).ShouldBeEmpty();
DanglingFor(later, lateTag2).ShouldBeEmpty();
}
/// <summary>
/// When the snapshot read materialises the seeded device (Devices is read before Tags), commits a NEW device and a
/// tag under it — one consistent transaction — on a separate connection.
/// </summary>
private sealed class CommitDeviceAndTagWhenDeviceMaterialises(
string connectionString, string triggerDeviceId, string driverId, string newDeviceId, string newTagId)
: IMaterializationInterceptor
{
private int _fired;
public object InitializedInstance(MaterializationInterceptionData materializationData, object entity)
{
if (entity is Device d && d.DeviceId == triggerDeviceId && Interlocked.Exchange(ref _fired, 1) == 0)
{
using var other = new OtOpcUaConfigDbContext(
new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(connectionString).Options);
other.Devices.Add(new Device { DeviceId = newDeviceId, DriverInstanceId = driverId, Name = newDeviceId, DeviceConfig = "{}" });
other.Tags.Add(NewTag(newTagId, newDeviceId));
other.SaveChanges();
}
return entity;
}
}
}
@@ -0,0 +1,202 @@
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Clusters;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages;
/// <summary>
/// lmxopcua#1049 (#998 C-9 follow-up): the NodeEdit / ClusterEdit pages against a REAL SQL Server, where
/// <c>rowversion</c> is generated and the Restrict FKs exist (the InMemory provider has neither). A save carrying
/// the token the page loaded is refused once another user has changed the row — the other user's edit survives —
/// and a save with a current token succeeds; a node that was deployed to deletes together with its
/// <c>NodeDeploymentState</c> rows; a cluster that still has nodes is not deleted and the page says why.
/// </summary>
[Collection(nameof(AdminUiSqlServerCollection))]
public sealed class ClusterNodeEditConcurrencySqlServerTests : BunitContext
{
private const string ModalSelector = ".modal-dialog";
private readonly AdminUiSqlServerFixture _sql;
/// <summary>Registers the fixture's SQL-backed context factory (when the server is available).</summary>
/// <param name="sql">The AdminUI SQL Server fixture.</param>
public ClusterNodeEditConcurrencySqlServerTests(AdminUiSqlServerFixture sql)
{
_sql = sql;
JSInterop.Setup<bool>("otDialog.activate", _ => true).SetResult(true);
JSInterop.SetupVoid("otDialog.update", _ => true).SetVoidResult();
JSInterop.SetupVoid("otDialog.deactivate", _ => true).SetVoidResult();
if (sql.SkipReason is null) Services.AddSingleton(sql.Factory);
Services.AddSingleton<AuthenticationStateProvider>(new FakeAuth());
}
private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}"[..(prefix.Length + 21)];
private string SeedCluster()
{
var clusterId = Id("C");
using var db = _sql.Factory.CreateDbContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "s1", NodeCount = 1,
RedundancyMode = RedundancyMode.None, CreatedBy = "t1049",
});
db.SaveChanges();
return clusterId;
}
private string SeedNode(string clusterId)
{
var nodeId = Id("n");
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.Add(new ClusterNode
{
NodeId = nodeId, ClusterId = clusterId, Host = "h-original", ApplicationUri = "urn:" + nodeId, CreatedBy = "t1049",
});
db.SaveChanges();
return nodeId;
}
/// <summary>Another user's committed edit, on its own context.</summary>
private void ConcurrentEdit(Action<OtOpcUaConfigDbContext> edit)
{
using var db = _sql.Factory.CreateDbContext();
edit(db);
db.SaveChanges();
}
/// <summary>NodeEdit: a stale token is refused with the concurrency message; the other user's edit survives.</summary>
[SqlServerFact]
public void NodeEdit_save_with_a_stale_token_is_refused()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var cut = Render<NodeEdit>(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId));
cut.WaitForAssertion(() => cut.Find("#host").GetAttribute("value").ShouldBe("h-original"));
ConcurrentEdit(db => db.ClusterNodes.Single(n => n.NodeId == nodeId).Host = "h-other-user");
cut.Find("#host").Change("h-stale");
cut.Find("form").Submit();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Another user changed this node"));
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).Host.ShouldBe("h-other-user");
}
/// <summary>Positive control: with no concurrent edit the same save goes through.</summary>
[SqlServerFact]
public void NodeEdit_save_with_a_current_token_succeeds()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var cut = Render<NodeEdit>(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId));
cut.WaitForAssertion(() => cut.Find("#host").GetAttribute("value").ShouldBe("h-original"));
cut.Find("#host").Change("h-saved");
cut.Find("form").Submit();
cut.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).Host.ShouldBe("h-saved");
});
cut.Markup.ShouldNotContain("Another user changed this node");
}
/// <summary>ClusterEdit: a stale token is refused; positive control on the same page after a reload-equivalent re-render.</summary>
[SqlServerFact]
public void ClusterEdit_save_with_a_stale_token_is_refused()
{
var clusterId = SeedCluster();
var cut = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, clusterId));
cut.WaitForAssertion(() => cut.Find("#notes"));
ConcurrentEdit(db => db.ServerClusters.Single(c => c.ClusterId == clusterId).Notes = "other user");
cut.Find("#notes").Change("stale");
cut.Find("form").Submit();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Another user changed this cluster"));
using (var db = _sql.Factory.CreateDbContext())
db.ServerClusters.AsNoTracking().Single(c => c.ClusterId == clusterId).Notes.ShouldBe("other user");
var fresh = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, clusterId));
fresh.WaitForAssertion(() => fresh.Find("#notes"));
fresh.Find("#notes").Change("current");
fresh.Find("form").Submit();
fresh.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ServerClusters.AsNoTracking().Single(c => c.ClusterId == clusterId).Notes.ShouldBe("current");
});
}
/// <summary>A node with NodeDeploymentState rows (Restrict FK) deletes together with them — no raw FK error.</summary>
[SqlServerFact]
public void NodeEdit_delete_of_a_deployed_node_removes_its_deployment_states()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var deploymentId = Guid.NewGuid();
using (var seed = _sql.Factory.CreateDbContext())
{
seed.Deployments.Add(new Deployment { DeploymentId = deploymentId, RevisionHash = new string('a', 64), CreatedBy = "t1049" });
seed.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = nodeId, DeploymentId = deploymentId, Status = NodeDeploymentStatus.Applied });
seed.SaveChanges();
}
var cut = Render<NodeEdit>(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId));
cut.WaitForAssertion(() => cut.Find("button.btn-outline-danger"));
cut.Find("button.btn-outline-danger").Click();
cut.Find(".modal-footer .btn-danger").Click();
cut.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.Any(n => n.NodeId == nodeId).ShouldBeFalse();
db.NodeDeploymentStates.Any(s => s.NodeId == nodeId).ShouldBeFalse();
db.Deployments.Any(d => d.DeploymentId == deploymentId).ShouldBeTrue(); // the deployment itself is history, kept
});
}
/// <summary>A cluster that still has nodes is not deleted (Restrict FK) and the page names the reason; positive control: an empty one deletes.</summary>
[SqlServerFact]
public void ClusterEdit_delete_of_a_cluster_with_nodes_is_refused_with_a_reason()
{
var busy = SeedCluster();
SeedNode(busy);
var cut = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, busy));
cut.WaitForAssertion(() => cut.Find("button.btn-outline-danger"));
cut.Find("button.btn-outline-danger").Click();
cut.Find(".modal-footer .btn-danger").Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("remove them first"));
using (var db = _sql.Factory.CreateDbContext())
db.ServerClusters.Any(c => c.ClusterId == busy).ShouldBeTrue();
var empty = SeedCluster();
var cut2 = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, empty));
cut2.WaitForAssertion(() => cut2.Find("button.btn-outline-danger"));
cut2.Find("button.btn-outline-danger").Click();
cut2.Find(".modal-footer .btn-danger").Click();
cut2.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ServerClusters.Any(c => c.ClusterId == empty).ShouldBeFalse();
});
}
private sealed class FakeAuth : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
Task.FromResult(new AuthenticationState(new System.Security.Claims.ClaimsPrincipal(
new System.Security.Claims.ClaimsIdentity("test"))));
}
}