Merge #998: ZTag/SAPID + historian-tagname duplicate gate rules, DanglingReference rule, filtered unique indexes fixed, RowVersion on ClusterNode/ServerCluster

This commit is contained in:
Joseph Doherty
2026-12-03 10:50:14 -05:00
24 changed files with 2833 additions and 171 deletions
+4
View File
@@ -152,6 +152,10 @@ historian tag OtOpcUa never provisions (`AddressSpaceApplier.IsOwnedHistorizedVa
recorder); node-inert ⇒ surgical; not mirrored on UNS refs; a non-bool value is the deploy error `HistorianReadOnlyInvalid`. The
default for an explicit `historianTagname` is still OWNED (overrides pin owned history across renames). `docs/Historian.md`
§"Read-only bindings to existing historian tags (#899)".
**Duplicate tagnames (#998):** two OWNED historized tags in one cluster whose effective tagname (the `historianTagname` override, else
the RawPath; case-insensitive) is equal are the deploy error `HistorianTagnameDuplicate` (`DraftValidator.ValidateHistorianTagnameUniqueness`) —
else both streams record into ONE historian tag and HistoryRead interleaves two signals. `historianReadOnly` tags are exempt (never provisioned
or recorded, so several may read one historian tag); clusters are checked separately (they may front different historians).
### Gateway-side prerequisites
+10
View File
@@ -144,6 +144,16 @@ removed (terminal Bad, then `RemoveVariableNode`, which severs the backing raw n
inverse `Organizes` edge) **before** the equipment subtree, and the subtree removal severs
the same edge for anything it reaches itself (archreview 03/P5 + 03/S20).
## Deploy-gate integrity rules (lmxopcua#998)
The parent links of the config tables (Tag→Device/TagGroup, Device→DriverInstance, Equipment→UnsLine, reference→Tag/Equipment, ...) are
**logical** foreign keys only, and the service-layer "is it empty?" delete checks are not serialised against a concurrent add. The deploy gate
(`DraftValidator.ValidateDanglingReferences`) therefore names every orphan as `DanglingReference` instead of letting each composer silently skip a
row with no path. Also enforced at the gate: fleet-wide `Equipment.ZTag` / `SAPID` uniqueness (`BadDuplicateExternalIdentifier`; see
`docs/Reservations.md`) and duplicate owned historian tagnames (`HistorianTagnameDuplicate`, `.claude/rules/historian.md`). The never-firing
`PathTooLong` and `EquipmentUuidImmutable` rules were deleted (the UnsSegment charset already bounds the path at 164 chars; no prior-generation
table exists to diff).
## The `Calculation` driver
Signal-level calculated tags are ordinary raw tags bound to a `Calculation` driver
+11
View File
@@ -1,5 +1,16 @@
# External-ID Reservations
> **Status (lmxopcua#998, 2026-12): the reservation ledger has no writer.** `sp_PublishGeneration`, the only code
> that inserted `ExternalIdReservation` rows, was retired with the generation model (it now only `RAISERROR`s), so the
> table stays empty and the pre-flight below can only fire against rows an operator inserted by hand. **Fleet-wide
> ZTag / SAPID uniqueness is now enforced by the deploy gate itself**: `DraftValidator.ValidateEquipmentExternalIdUniqueness`
> groups every equipment row in the (whole-DB) draft snapshot by trimmed, case-insensitive ZTag and by SAPID and
> reports each duplicate as `BadDuplicateExternalIdentifier` naming the other equipment (same cluster or not).
> Blank values mean "no identifier". The permanent-claim semantics described below (a retired asset's id staying
> reserved) are **not** provided; the table, `/reservations` page and release procedure remain for any rows that
> already exist. The equipment page's field hint says "rejected when you deploy", matching this. A filtered unique
> index on `Equipment.ZTag` / `SAPID` was not added (needs a duplicate pre-clean migration); the gate is the authority.
The reservation subsystem guarantees that an asset's **external identifiers**
— its `ZTag` and `SAPID` — belong to exactly one piece of equipment across the
entire fleet, for all time. It is the mechanism that stops two pieces of
@@ -103,6 +103,12 @@ public sealed class ClusterNode
/// <summary>Gets or sets the username of who created this node.</summary>
public required string CreatedBy { get; set; }
/// <summary>
/// Optimistic-concurrency token (#998, review C-9). <see cref="Enabled"/> / <see cref="MaintenanceMode"/> define a
/// deploy's expected-ack set, so a stale edit form must not silently overwrite a concurrent change.
/// </summary>
public byte[] RowVersion { get; set; } = Array.Empty<byte>();
// Navigation
/// <summary>Gets or sets the cluster this node belongs to.</summary>
public ServerCluster? Cluster { get; set; }
@@ -32,10 +32,10 @@ public sealed class Equipment
/// <summary>Operator colloquial id (e.g. "machine_001"). Unique within cluster. Required.</summary>
public required string MachineCode { get; set; }
/// <summary>ERP equipment id. Unique fleet-wide via <see cref="ExternalIdReservation"/>. Primary browse identifier in Admin UI.</summary>
/// <summary>ERP equipment id. Unique fleet-wide, enforced by the deploy gate (<c>DraftValidator</c>, <c>BadDuplicateExternalIdentifier</c>; #998). Primary browse identifier in Admin UI.</summary>
public string? ZTag { get; set; }
/// <summary>SAP PM equipment id. Unique fleet-wide via <see cref="ExternalIdReservation"/>.</summary>
/// <summary>SAP PM equipment id. Unique fleet-wide, enforced by the deploy gate (<c>DraftValidator</c>; #998).</summary>
public string? SAPID { get; set; }
// OPC UA Companion Spec OPC 40010 Machinery Identification fields.
@@ -44,6 +44,9 @@ public sealed class ServerCluster
/// <summary>Gets or sets the user who last modified the cluster.</summary>
public string? ModifiedBy { get; set; }
/// <summary>Optimistic-concurrency token (#998, review C-9): a stale cluster edit form must not silently overwrite a concurrent change.</summary>
public byte[] RowVersion { get; set; } = Array.Empty<byte>();
// Navigation
/// <summary>Gets or sets the collection of cluster nodes.</summary>
public ICollection<ClusterNode> Nodes { get; set; } = [];
@@ -0,0 +1,98 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
{
/// <summary>
/// lmxopcua#998 (review C-8, C-9). C-8: <c>UX_NodeAcl_PrincipalScope</c> and
/// <c>UX_LdapGroupRoleMapping_Group_Cluster</c> were created with EF's implicit <c>WHERE [col] IS NOT NULL</c>
/// filter, so NULL-keyed rows (Cluster-kind ACLs, system-wide LDAP mappings) were unconstrained although the model
/// comment promised one row per key. Recreated unfiltered (SQL Server treats NULLs as equal in a unique index).
/// Rows that duplicated in the meantime would make the CREATE fail halfway, so a pre-check names them first.
/// C-9: <c>RowVersion</c> concurrency tokens on <c>ServerCluster</c> and <c>ClusterNode</c>.
/// </summary>
public partial class ConfigurationGapsIndexesAndRowVersions : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(@"
IF EXISTS (SELECT 1 FROM [NodeAcl] GROUP BY [ClusterId], [Principal], [ScopeKind], [ScopeId] HAVING COUNT(*) > 1)
THROW 50998, 'ConfigurationGapsIndexesAndRowVersions: duplicate NodeAcl rows exist for one (ClusterId, Principal, ScopeKind, ScopeId) - typically several Cluster-scope rows for one principal. Delete or merge the duplicates, then re-run.', 1;
IF EXISTS (SELECT 1 FROM [LdapGroupRoleMapping] GROUP BY [LdapGroup], [ClusterId] HAVING COUNT(*) > 1)
THROW 50998, 'ConfigurationGapsIndexesAndRowVersions: duplicate LdapGroupRoleMapping rows exist for one (LdapGroup, ClusterId) - typically several system-wide rows for one group. Delete or merge the duplicates, then re-run.', 1;
");
migrationBuilder.DropIndex(
name: "UX_NodeAcl_PrincipalScope",
table: "NodeAcl");
migrationBuilder.DropIndex(
name: "UX_LdapGroupRoleMapping_Group_Cluster",
table: "LdapGroupRoleMapping");
migrationBuilder.AddColumn<byte[]>(
name: "RowVersion",
table: "ServerCluster",
type: "rowversion",
rowVersion: true,
nullable: false,
defaultValue: new byte[0]);
migrationBuilder.AddColumn<byte[]>(
name: "RowVersion",
table: "ClusterNode",
type: "rowversion",
rowVersion: true,
nullable: false,
defaultValue: new byte[0]);
migrationBuilder.CreateIndex(
name: "UX_NodeAcl_PrincipalScope",
table: "NodeAcl",
columns: new[] { "ClusterId", "Principal", "ScopeKind", "ScopeId" },
unique: true);
migrationBuilder.CreateIndex(
name: "UX_LdapGroupRoleMapping_Group_Cluster",
table: "LdapGroupRoleMapping",
columns: new[] { "LdapGroup", "ClusterId" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "UX_NodeAcl_PrincipalScope",
table: "NodeAcl");
migrationBuilder.DropIndex(
name: "UX_LdapGroupRoleMapping_Group_Cluster",
table: "LdapGroupRoleMapping");
migrationBuilder.DropColumn(
name: "RowVersion",
table: "ServerCluster");
migrationBuilder.DropColumn(
name: "RowVersion",
table: "ClusterNode");
migrationBuilder.CreateIndex(
name: "UX_NodeAcl_PrincipalScope",
table: "NodeAcl",
columns: new[] { "ClusterId", "Principal", "ScopeKind", "ScopeId" },
unique: true,
filter: "[ScopeId] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "UX_LdapGroupRoleMapping_Group_Cluster",
table: "LdapGroupRoleMapping",
columns: new[] { "LdapGroup", "ClusterId" },
unique: true,
filter: "[ClusterId] IS NOT NULL");
}
}
}
@@ -156,6 +156,12 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.Property<int>("OpcUaPort")
.HasColumnType("int");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.Property<byte>("ServiceLevelBase")
.HasColumnType("tinyint");
@@ -978,8 +984,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.HasIndex("LdapGroup", "ClusterId")
.IsUnique()
.HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster")
.HasFilter("[ClusterId] IS NOT NULL");
.HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster");
b.ToTable("LdapGroupRoleMapping", (string)null);
});
@@ -1046,8 +1051,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.HasIndex("ClusterId", "Principal", "ScopeKind", "ScopeId")
.IsUnique()
.HasDatabaseName("UX_NodeAcl_PrincipalScope")
.HasFilter("[ScopeId] IS NOT NULL");
.HasDatabaseName("UX_NodeAcl_PrincipalScope");
b.ToTable("NodeAcl", (string)null);
});
@@ -1507,6 +1511,12 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
.HasMaxLength(16)
.HasColumnType("nvarchar(16)");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.Property<string>("Site")
.IsRequired()
.HasMaxLength(32)
@@ -192,6 +192,7 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.Property(x => x.CreatedBy).HasMaxLength(128);
e.Property(x => x.ModifiedAt).HasColumnType("datetime2(3)");
e.Property(x => x.ModifiedBy).HasMaxLength(128);
e.Property(x => x.RowVersion).IsRowVersion();
e.HasIndex(x => x.Name).IsUnique().HasDatabaseName("UX_ServerCluster_Name");
e.HasIndex(x => x.Site).HasDatabaseName("IX_ServerCluster_Site");
});
@@ -216,6 +217,7 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.Property(x => x.LastSeenAt).HasColumnType("datetime2(3)");
e.Property(x => x.CreatedAt).HasColumnType("datetime2(3)").HasDefaultValueSql("SYSUTCDATETIME()");
e.Property(x => x.CreatedBy).HasMaxLength(128);
e.Property(x => x.RowVersion).IsRowVersion();
e.HasOne(x => x.Cluster).WithMany(c => c.Nodes)
.HasForeignKey(x => x.ClusterId)
@@ -560,7 +562,12 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
.HasFilter("[ScopeId] IS NOT NULL")
.HasDatabaseName("IX_NodeAcl_Scope");
e.HasIndex(x => x.NodeAclId).IsUnique().HasDatabaseName("UX_NodeAcl_LogicalId");
// #998 (review C-8): HasFilter(null) is explicit — without it the SQL Server provider adds
// `WHERE [ScopeId] IS NOT NULL` to a unique index over a nullable column, which would leave the
// Cluster-kind rows (the only kind with a NULL ScopeId) unconstrained. Unfiltered, SQL Server treats
// NULL as one value, so there is at most ONE Cluster-scope row per (cluster, principal).
e.HasIndex(x => new { x.ClusterId, x.Principal, x.ScopeKind, x.ScopeId }).IsUnique()
.HasFilter(null)
.HasDatabaseName("UX_NodeAcl_PrincipalScope");
});
}
@@ -667,12 +674,14 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
.HasForeignKey(x => x.ClusterId)
.OnDelete(DeleteBehavior.Cascade);
// Uniqueness: one row per (LdapGroup, ClusterId). Null ClusterId is treated as its own
// "bucket" so a system-wide row coexists with cluster-scoped rows for the same group.
// SQL Server treats NULL as a distinct value in unique-index comparisons by default
// since 2008 SP1 onwards under the session setting we use — tested in SchemaCompliance.
// Uniqueness: one row per (LdapGroup, ClusterId). A NULL ClusterId (system-wide) is its own
// bucket: one system-wide row per group, coexisting with cluster-scoped rows for that group.
// #998 (review C-8): SQL Server treats NULLs as EQUAL in a unique index, but the provider adds
// `WHERE [ClusterId] IS NOT NULL` to a unique index over a nullable column unless the filter is
// set explicitly — which silently exempted exactly the system-wide rows. HasFilter(null) opts out.
e.HasIndex(x => new { x.LdapGroup, x.ClusterId })
.IsUnique()
.HasFilter(null)
.HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster");
// Hot-path lookup during cookie auth: "what grants does this user's set of LDAP
@@ -59,6 +59,18 @@ public sealed class LdapGroupRoleMappingService(IDbContextFactory<OtOpcUaConfigD
if (row.CreatedAtUtc == default) row.CreatedAtUtc = DateTime.UtcNow;
await using var db = await dbFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
// #998 (review C-8): one row per (LdapGroup, ClusterId); a NULL ClusterId (system-wide) is its own bucket.
// UX_LdapGroupRoleMapping_Group_Cluster enforces it, but say it in words instead of a raw DbUpdateException.
var duplicate = await db.LdapGroupRoleMappings
.AnyAsync(m => m.LdapGroup == row.LdapGroup && m.ClusterId == row.ClusterId, cancellationToken)
.ConfigureAwait(false);
if (duplicate)
throw new InvalidLdapGroupRoleMappingException(
$"A mapping for group '{row.LdapGroup}' already exists for " +
(row.ClusterId is null ? "the whole fleet (system-wide)" : $"cluster '{row.ClusterId}'") +
"; delete or change that row instead of adding a second one.");
db.LdapGroupRoleMappings.Add(row);
await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return row;
@@ -15,18 +15,6 @@ public sealed class DraftSnapshot
/// <summary>Gets the cluster identifier.</summary>
public required string ClusterId { get; init; }
/// <summary>
/// Cluster's Enterprise segment (UNS level 1). When set, <see cref="DraftValidator"/> uses
/// the actual length for path-length checks instead of a conservative 32-char upper bound.
/// </summary>
public string? Enterprise { get; init; }
/// <summary>
/// Cluster's Site segment (UNS level 2). When set, <see cref="DraftValidator"/> uses the
/// actual length for path-length checks instead of a conservative 32-char upper bound.
/// </summary>
public string? Site { get; init; }
// v3: the Namespace entity is retired (the two OPC UA namespaces are implicit). The Raw tree
// (RawFolders → DriverInstances → Devices → TagGroups → Tags) + the UNS projection
// (UnsTagReferences) feed the v3 validator rules (raw-name charset, historized-tagname length, UNS
@@ -90,9 +78,6 @@ public sealed class DraftSnapshot
/// </summary>
public IReadOnlyList<ApiKey> ApiKeys { get; init; } = [];
/// <summary>Prior Equipment rows (any generation, same cluster) for stability checks.</summary>
public IReadOnlyList<Equipment> PriorEquipment { get; init; } = [];
/// <summary>Active reservations (<c>ReleasedAt IS NULL</c>) for pre-flight.</summary>
public IReadOnlyList<ExternalIdReservation> ActiveReservations { get; init; } = [];
}
@@ -17,10 +17,9 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;
/// </para>
/// <para>
/// <see cref="DraftSnapshot.GenerationId"/> is a placeholder (the generation model was
/// dropped); no rule reads it. <see cref="DraftSnapshot.PriorEquipment"/> is empty because
/// there is no prior-generation table to diff against. <see cref="DraftSnapshot.Enterprise"/>
/// / <see cref="DraftSnapshot.Site"/> are left null so the path-length rule uses its
/// conservative upper bound.
/// dropped); no rule reads it. (The prior-generation / path-length inputs
/// <c>PriorEquipment</c>, <c>Enterprise</c> and <c>Site</c> were removed with their never-firing rules,
/// lmxopcua#998 review C-10.)
/// </para>
/// <para>
/// <b>One consistent read.</b> On a relational provider the tables are read inside a
@@ -97,7 +96,6 @@ public static class DraftSnapshotFactory
PollGroups = await db.PollGroups.AsNoTracking().OrderBy(x => x.PollGroupId).ToListAsync(ct),
NodeAcls = await db.NodeAcls.AsNoTracking().OrderBy(x => x.NodeAclId).ToListAsync(ct),
ApiKeys = await db.ApiKeys.AsNoTracking().OrderBy(x => x.ApiKeyId).ToListAsync(ct),
PriorEquipment = [], // intentional: no prior-generation table to diff against at this level
ActiveReservations = await db.ExternalIdReservations
.AsNoTracking()
.Where(r => r.ReleasedAt == null) // active only — matches DraftSnapshot.ActiveReservations semantics
@@ -16,8 +16,6 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;
/// </summary>
public static class DraftValidator
{
private const int MaxPathLength = 200;
/// <summary>
/// Validates a draft snapshot and returns all validation errors found in a single pass.
/// </summary>
@@ -28,8 +26,8 @@ public static class DraftValidator
var errors = new List<ValidationError>();
ValidateUnsSegments(draft, errors);
ValidatePathLength(draft, errors);
ValidateEquipmentUuidImmutability(draft, errors);
ValidateDanglingReferences(draft, errors);
ValidateEquipmentExternalIdUniqueness(draft, errors);
ValidateReservationPreflight(draft, errors);
ValidateEquipmentIdDerivation(draft, errors);
@@ -37,6 +35,7 @@ public static class DraftValidator
// and ValidateGalaxyTagFullName (blob-as-identity gone) are replaced by:
ValidateRawNameCharset(draft, errors);
ValidateHistorizedTagnameLength(draft, errors);
ValidateHistorianTagnameUniqueness(draft, errors);
ValidateHistorianReadOnly(draft, errors);
ValidateUnsLeafNames(draft, errors);
ValidateUnsEffectiveLeafUniqueness(draft, errors);
@@ -453,7 +452,7 @@ public static class DraftValidator
var graph = new DependencyGraph();
foreach (var (_, rawPath, scriptId) in calcTags)
{
if (rawPath is null) continue; // broken chain — flagged by the charset rule; not a graph node
if (rawPath is null) continue; // broken chain — flagged by DanglingReference; not a graph node
var source = scriptId is not null && scriptSourceById.TryGetValue(scriptId, out var src) ? src : null;
var calcDeps = EquipmentScriptPaths.ExtractDependencyRefs(source)
.Where(calcRawPaths.Contains)
@@ -721,7 +720,7 @@ public static class DraftValidator
var intent = TagConfigIntent.Parse(t.TagConfig);
if (!intent.IsHistorized) continue;
// Effective tagname = explicit override else the computed RawPath (null when the chain is broken —
// a separate rule/charset check flags that; nothing to length-check here).
// DanglingReference flags that; nothing to length-check here).
var effective = intent.HistorianTagname ?? resolver.TryBuildTagPath(t.DeviceId, t.TagGroupId, t.Name);
if (effective is null || effective.Length <= MaxHistorianTagname) continue;
errors.Add(new("HistorianTagnameTooLong",
@@ -949,45 +948,150 @@ public static class DraftValidator
errors.Add(new("UnsSegmentInvalid", UnsSegment.Describe("Equipment.Name", e.Name), e.EquipmentId));
}
/// <summary>Cluster.Enterprise + Site + area + line + equipment + 4 slashes ≤ 200 chars.</summary>
private static void ValidatePathLength(DraftSnapshot draft, List<ValidationError> errors)
/// <summary>The <c>DanglingReference</c> error code (lmxopcua#998, review C-10).</summary>
public const string DanglingReferenceCode = "DanglingReference";
/// <summary>The <c>HistorianTagnameDuplicate</c> error code (lmxopcua#998, review C-5).</summary>
public const string HistorianTagnameDuplicateCode = "HistorianTagnameDuplicate";
/// <summary>The ZTag / SAPID duplicate error code (decision #124's name, now raised from the draft itself).</summary>
public const string DuplicateExternalIdentifierCode = "BadDuplicateExternalIdentifier";
/// <summary>
/// lmxopcua#998 (review C-10): the parent links of the config tables are LOGICAL foreign keys only (no DB FK —
/// see <c>OtOpcUaConfigDbContext</c>), and the service-layer "is it empty?" checks before a delete are not
/// serialised against a concurrent add. User A deleting an empty Device while user B adds a Tag under it
/// therefore commits both, leaving a row with no RawPath that every rule and every composer silently skips.
/// This rule is the single authority that names such orphans at the deploy gate:
/// Tag→Device, Tag→TagGroup, TagGroup→Device / parent TagGroup, Device→DriverInstance,
/// DriverInstance→RawFolder, RawFolder→parent RawFolder, UnsLine→UnsArea, Equipment→UnsLine,
/// UnsTagReference→Tag / Equipment, VirtualTag / ScriptedAlarm→Equipment.
/// </summary>
private static void ValidateDanglingReferences(DraftSnapshot draft, List<ValidationError> errors)
{
// Use actual Enterprise/Site lengths when the snapshot carries them (populated by
// DraftValidationService from the ServerCluster row). Fall back to a conservative
// 32-char upper bound per segment when not supplied — over-penalises short values
// but never under-penalises long ones, which is acceptable for the fallback case.
var enterpriseLen = draft.Enterprise?.Length ?? 32;
var siteLen = draft.Site?.Length ?? 32;
HashSet<string> Ids<T>(IEnumerable<T> rows, Func<T, string> id) =>
rows.Select(id).ToHashSet(StringComparer.Ordinal);
var areaById = draft.UnsAreas.ToDictionary(a => a.UnsAreaId);
var lineById = draft.UnsLines.ToDictionary(l => l.UnsLineId);
var folders = Ids(draft.RawFolders, f => f.RawFolderId);
var drivers = Ids(draft.DriverInstances, d => d.DriverInstanceId);
var devices = Ids(draft.Devices, d => d.DeviceId);
var groups = Ids(draft.TagGroups, g => g.TagGroupId);
var tags = Ids(draft.Tags, t => t.TagId);
var areas = Ids(draft.UnsAreas, a => a.UnsAreaId);
var lines = Ids(draft.UnsLines, l => l.UnsLineId);
var equipment = Ids(draft.Equipment, e => e.EquipmentId);
foreach (var eq in draft.Equipment.Where(e => e.UnsLineId is not null))
void Check(HashSet<string> parents, string? parentId, string kind, string id, string parentKind)
{
if (!lineById.TryGetValue(eq.UnsLineId!, out var line)) continue;
if (!areaById.TryGetValue(line.UnsAreaId, out var area)) continue;
if (string.IsNullOrEmpty(parentId) || parents.Contains(parentId)) return;
errors.Add(new(DanglingReferenceCode,
$"{kind} '{id}' references {parentKind} '{parentId}', which does not exist (deleted concurrently?) — " +
$"the {kind} has no path and would be skipped by the deploy; delete or re-parent it",
id));
}
var len = enterpriseLen + siteLen + area.Name.Length + line.Name.Length + eq.Name.Length + 4;
if (len > MaxPathLength)
errors.Add(new("PathTooLong",
$"Equipment path exceeds {MaxPathLength} chars (approx {len})",
eq.EquipmentId));
foreach (var f in draft.RawFolders) Check(folders, f.ParentRawFolderId, "RawFolder", f.RawFolderId, "parent RawFolder");
foreach (var d in draft.DriverInstances) Check(folders, d.RawFolderId, "DriverInstance", d.DriverInstanceId, "RawFolder");
foreach (var d in draft.Devices) Check(drivers, d.DriverInstanceId, "Device", d.DeviceId, "DriverInstance");
foreach (var g in draft.TagGroups)
{
Check(devices, g.DeviceId, "TagGroup", g.TagGroupId, "Device");
Check(groups, g.ParentTagGroupId, "TagGroup", g.TagGroupId, "parent TagGroup");
}
foreach (var t in draft.Tags)
{
Check(devices, t.DeviceId, "Tag", t.TagId, "Device");
Check(groups, t.TagGroupId, "Tag", t.TagId, "TagGroup");
}
foreach (var l in draft.UnsLines) Check(areas, l.UnsAreaId, "UnsLine", l.UnsLineId, "UnsArea");
foreach (var e in draft.Equipment) Check(lines, e.UnsLineId, "Equipment", e.EquipmentId, "UnsLine");
foreach (var r in draft.UnsTagReferences)
{
Check(tags, r.TagId, "UnsTagReference", r.UnsTagReferenceId, "Tag");
Check(equipment, r.EquipmentId, "UnsTagReference", r.UnsTagReferenceId, "Equipment");
}
foreach (var v in draft.VirtualTags) Check(equipment, v.EquipmentId, "VirtualTag", v.VirtualTagId, "Equipment");
foreach (var a in draft.ScriptedAlarms) Check(equipment, a.EquipmentId, "ScriptedAlarm", a.ScriptedAlarmId, "Equipment");
}
/// <summary>
/// lmxopcua#998 (review C-5): two OWNED historized tags must not resolve to the same effective historian
/// tagname (the <c>historianTagname</c> override, else the RawPath), compared case-insensitively — AVEVA
/// historian tagnames are. A copied override (a tag duplicated in <c>/raw</c> or CSV-imported from a template)
/// would otherwise provision ONE historian tag and record both signals into it, so HistoryRead through either
/// NodeId returns the interleaved values of two different signals.
/// <para>Decisions: a <c>historianReadOnly</c> tag is exempt — OtOpcUa neither provisions nor records into it,
/// so several read-only bindings (or a read-only alias of an owned tag) legitimately read the same historian
/// tag. The check is scoped per cluster: RawPaths are only unique within a cluster and clusters may front
/// different historians, so a cross-cluster name match is not provably a collision.</para>
/// </summary>
private static void ValidateHistorianTagnameUniqueness(DraftSnapshot draft, List<ValidationError> errors)
{
var resolver = BuildRawPathResolver(draft);
var clusterByDriver = draft.DriverInstances.GroupBy(d => d.DriverInstanceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().ClusterId, StringComparer.Ordinal);
var clusterByDevice = draft.Devices.GroupBy(d => d.DeviceId, StringComparer.Ordinal)
.ToDictionary(
g => g.Key,
g => clusterByDriver.TryGetValue(g.First().DriverInstanceId, out var c) ? c : string.Empty,
StringComparer.Ordinal);
var owners = new List<(string Cluster, string Tagname, string TagId)>();
foreach (var t in draft.Tags)
{
var intent = TagConfigIntent.Parse(t.TagConfig);
if (!intent.IsHistorized || intent.HistorianReadOnly) continue;
var effective = intent.HistorianTagname ?? resolver.TryBuildTagPath(t.DeviceId, t.TagGroupId, t.Name);
if (string.IsNullOrWhiteSpace(effective)) continue;
clusterByDevice.TryGetValue(t.DeviceId, out var cluster);
owners.Add((cluster ?? string.Empty, effective, t.TagId));
}
foreach (var g in owners.GroupBy(o => (o.Cluster, Name: o.Tagname.ToUpperInvariant())))
{
var members = g.ToList();
if (members.Count < 2) continue;
foreach (var m in members)
{
var others = string.Join(", ", members.Where(o => o.TagId != m.TagId).Select(o => $"'{o.TagId}'"));
errors.Add(new(HistorianTagnameDuplicateCode,
$"tag '{m.TagId}' historian tagname '{m.Tagname}' is also the effective tagname of {others}; " +
"both would be recorded into one historian tag. Give one a distinct 'historianTagname' override, " +
"or mark the others 'historianReadOnly'",
m.TagId));
}
}
}
private static void ValidateEquipmentUuidImmutability(DraftSnapshot draft, List<ValidationError> errors)
/// <summary>
/// lmxopcua#998 (review C-3): <c>Equipment.ZTag</c> and <c>Equipment.SAPID</c> are unique fleet-wide. The
/// former writer of the reservation ledger (<c>sp_PublishGeneration</c>) is gone, so
/// <see cref="ValidateReservationPreflight"/> alone enforced nothing; the draft snapshot is the whole config
/// DB (every cluster), so the duplicate check is done here, on the draft, which IS the authority.
/// Compared trimmed and case-insensitively (the DB collation is); blank values mean "no identifier".
/// </summary>
private static void ValidateEquipmentExternalIdUniqueness(DraftSnapshot draft, List<ValidationError> errors)
{
var priorById = draft.PriorEquipment
.GroupBy(e => e.EquipmentId)
.ToDictionary(g => g.Key, g => g.First().EquipmentUuid);
foreach (var eq in draft.Equipment)
void Check(string label, Func<Equipment, string?> selector)
{
if (priorById.TryGetValue(eq.EquipmentId, out var priorUuid) && priorUuid != eq.EquipmentUuid)
errors.Add(new("EquipmentUuidImmutable",
$"EquipmentId '{eq.EquipmentId}' had UUID '{priorUuid}' in a prior generation; cannot change to '{eq.EquipmentUuid}'",
eq.EquipmentId));
foreach (var g in draft.Equipment
.Where(e => !string.IsNullOrWhiteSpace(selector(e)))
.GroupBy(e => selector(e)!.Trim(), StringComparer.OrdinalIgnoreCase))
{
var members = g.ToList();
if (members.Count < 2) continue;
foreach (var e in members)
{
var others = string.Join(", ", members.Where(o => o.EquipmentId != e.EquipmentId).Select(o => $"'{o.EquipmentId}'"));
errors.Add(new(DuplicateExternalIdentifierCode,
$"{label} '{selector(e)!.Trim()}' of equipment '{e.EquipmentId}' is also set on {others}; a {label} must be unique fleet-wide",
e.EquipmentId));
}
}
}
Check("ZTag", e => e.ZTag);
Check("SAPID", e => e.SAPID);
}
private static void ValidateReservationPreflight(DraftSnapshot draft, List<ValidationError> errors)
@@ -252,6 +252,15 @@ else
if (!_scope.Ok) { _error = $"Scope: {_scope.Message}"; return; }
await using var db = await DbFactory.CreateDbContextAsync();
// #998 (review C-8): UX_NodeAcl_PrincipalScope allows one row per (cluster, principal, scope kind,
// scope id) — including one Cluster-scope row (NULL scope id). Report it in words.
var scopeId = string.IsNullOrWhiteSpace(_form.ScopeId) ? null : _form.ScopeId;
var editedId = IsNew ? _form.NodeAclId : NodeAclId;
if (await db.NodeAcls.AnyAsync(a => a.ClusterId == ClusterId && a.Principal == _form.Principal
&& a.ScopeKind == _form.ScopeKind && a.ScopeId == scopeId && a.NodeAclId != editedId))
{ _error = $"An ACL for '{_form.Principal}' at this scope already exists in this cluster; edit that row instead."; return; }
if (IsNew)
{
if (await db.NodeAcls.AnyAsync(a => a.NodeAclId == _form.NodeAclId))
@@ -139,6 +139,7 @@ else
RedundancyMode = _existing.RedundancyMode,
Enabled = _existing.Enabled,
Notes = _existing.Notes,
RowVersion = _existing.RowVersion,
};
}
_loaded = true;
@@ -154,6 +155,8 @@ else
var entity = await db.ServerClusters.FirstOrDefaultAsync(c => c.ClusterId == ClusterId);
if (entity is null) { _error = "Cluster no longer exists."; return; }
// #998 (review C-9): the token loaded with the form, so a stale form cannot overwrite a concurrent edit.
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
var auth = await AuthState.GetAuthenticationStateAsync();
entity.Name = _form.Name;
entity.Enterprise = _form.Enterprise;
@@ -168,6 +171,10 @@ else
await db.SaveChangesAsync();
Nav.NavigateTo($"/clusters/{ClusterId}");
}
catch (DbUpdateConcurrencyException)
{
_error = "Another user changed this cluster while you were editing. Reload the page and re-apply your change.";
}
catch (Exception ex)
{
_error = ex.Message;
@@ -209,5 +216,6 @@ else
public RedundancyMode RedundancyMode { get; set; } = RedundancyMode.None;
public bool Enabled { get; set; } = true;
public string? Notes { get; set; }
public byte[] RowVersion { get; set; } = [];
}
}
@@ -177,6 +177,7 @@ else
ServiceLevelBase = _existing.ServiceLevelBase,
Enabled = _existing.Enabled,
DriverConfigOverridesJson = _existing.DriverConfigOverridesJson,
RowVersion = _existing.RowVersion,
};
}
}
@@ -251,6 +252,9 @@ else
var entity = await db.ClusterNodes.FirstOrDefaultAsync(
n => n.ClusterId == ClusterId && n.NodeId == NodeId);
if (entity is null) { _error = "Row no longer exists."; return; }
// #998 (review C-9): the token loaded with the form, not the one just re-read — otherwise a
// concurrent edit (e.g. Enabled flipped for maintenance) would be silently overwritten.
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
entity.Host = _form.Host;
entity.OpcUaPort = _form.OpcUaPort;
entity.DashboardPort = _form.DashboardPort;
@@ -262,6 +266,10 @@ else
await db.SaveChangesAsync();
Nav.NavigateTo($"/clusters/{ClusterId}");
}
catch (DbUpdateConcurrencyException)
{
_error = "Another user changed this node while you were editing. Reload the page and re-apply your change.";
}
catch (Exception ex)
{
_error = ex.Message;
@@ -283,6 +291,10 @@ else
var entity = await db.ClusterNodes.FirstOrDefaultAsync(
n => n.ClusterId == ClusterId && n.NodeId == NodeId);
if (entity is null) { Nav.NavigateTo($"/clusters/{ClusterId}"); return; }
// #998 (review C-9): NodeDeploymentState.NodeId is a Restrict FK, so a node that was ever deployed
// to could not be deleted (raw FK error). Its per-deployment ack rows are history about THIS node
// and meaningless without it: remove them in the same transaction.
db.NodeDeploymentStates.RemoveRange(await db.NodeDeploymentStates.Where(s => s.NodeId == NodeId).ToListAsync());
db.ClusterNodes.Remove(entity);
await db.SaveChangesAsync();
Nav.NavigateTo($"/clusters/{ClusterId}");
@@ -321,5 +333,6 @@ else
[Range(0, 255)] public int ServiceLevelBase { get; set; } = 200;
public bool Enabled { get; set; } = true;
public string? DriverConfigOverridesJson { get; set; }
public byte[] RowVersion { get; set; } = [];
}
}
@@ -23,7 +23,7 @@ else
<h2 class="panel-head">@_rows.Count reservation@(_rows.Count == 1 ? "" : "s")</h2>
@if (_rows.Count == 0)
{
<div style="padding:1rem" class="text-muted">No reservations yet.</div>
<div style="padding:1rem" class="text-muted">No reservations. (Nothing writes this ledger any more: ZTag / SAPID uniqueness is enforced by the deploy gate.)</div>
}
else
{
@@ -117,11 +117,12 @@ else
<div class="col-md-6 mb-3">
<label class="form-label" for='@FieldId("eq-ztag")'>ZTag (ERP)</label>
<InputText id='@FieldId("eq-ztag")' aria-describedby='@FieldId("eq-ztag-hint")' @bind-Value="form.ZTag" class="form-control form-control-sm" />
<div id='@FieldId("eq-ztag-hint")' class="form-text">Unique fleet-wide via ExternalIdReservation.</div>
<div id='@FieldId("eq-ztag-hint")' class="form-text">Must be unique fleet-wide (case-insensitive); a duplicate is rejected when you deploy.</div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label" for='@FieldId("eq-sap")'>SAPID</label>
<InputText id='@FieldId("eq-sap")' @bind-Value="form.SAPID" class="form-control form-control-sm" />
<div class="form-text">Must be unique fleet-wide (case-insensitive); a duplicate is rejected when you deploy.</div>
</div>
</div>
<div class="mb-3">
@@ -0,0 +1,174 @@
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
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.Configuration.Tests;
/// <summary>
/// lmxopcua#998 (review 2026-12-02 03-configuration C-8, C-9) against the real SQL schema: the two unique
/// indexes over nullable columns must cover the NULL-key rows, and ClusterNode / ServerCluster carry a
/// concurrency token.
/// </summary>
[Trait("Category", "SchemaCompliance")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class ConfigurationGapsSchemaTests
{
private readonly SchemaComplianceFixture _fixture;
/// <summary>Initializes a new instance of the <see cref="ConfigurationGapsSchemaTests"/> class.</summary>
/// <param name="fixture">The schema compliance fixture (real SQL DB).</param>
public ConfigurationGapsSchemaTests(SchemaComplianceFixture fixture) => _fixture = fixture;
private OtOpcUaConfigDbContext NewContext() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(_fixture.ConnectionString).Options);
private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}";
private string SeedCluster()
{
var clusterId = Id("cl");
using var db = NewContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "dev", NodeCount = 1,
RedundancyMode = RedundancyMode.None, CreatedBy = "t998",
});
db.SaveChanges();
return clusterId;
}
private static NodeAcl ClusterAcl(string clusterId, string principal) => new()
{
NodeAclId = Id("acl"), ClusterId = clusterId, Principal = principal,
ScopeKind = NodeAclScopeKind.Cluster, ScopeId = null, PermissionFlags = NodePermissions.Browse,
};
/// <summary>The recorded index definitions are unfiltered (HasFilter(null)) — the model comment's "one row per key" holds for NULLs too.</summary>
[Fact]
public void The_two_nullable_unique_indexes_are_not_filtered()
{
using var db = NewContext();
var filtered = db.Database.SqlQueryRaw<string>(
"SELECT name AS Value FROM sys.indexes WHERE is_unique = 1 AND has_filter = 1 " +
"AND name IN ('UX_NodeAcl_PrincipalScope', 'UX_LdapGroupRoleMapping_Group_Cluster')").ToList();
filtered.ShouldBeEmpty();
}
/// <summary>Two system-wide mappings for one group (NULL ClusterId) now collide.</summary>
[Fact]
public void Two_system_wide_mappings_for_one_group_are_rejected()
{
var group = Id("cn=grp");
using var db = NewContext();
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Administrator, IsSystemWide = true });
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Designer, IsSystemWide = true });
Should.Throw<DbUpdateException>(() => db.SaveChanges());
}
/// <summary>Positive control: a system-wide row plus a cluster row, and one row for another group, are all fine.</summary>
[Fact]
public void System_wide_plus_cluster_scoped_and_other_groups_are_accepted()
{
var group = Id("cn=grp");
var cluster = SeedCluster();
using var db = NewContext();
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Administrator, IsSystemWide = true });
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Designer, ClusterId = cluster, IsSystemWide = false });
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = Id("cn=other"), Role = AdminRole.Administrator, IsSystemWide = true });
Should.NotThrow(() => db.SaveChanges());
}
/// <summary>Two Cluster-scope ACL rows (NULL ScopeId) for one principal in one cluster now collide.</summary>
[Fact]
public void Two_cluster_scope_acls_for_one_principal_are_rejected()
{
var cluster = SeedCluster();
using var db = NewContext();
db.NodeAcls.Add(ClusterAcl(cluster, "grp-a"));
db.NodeAcls.Add(ClusterAcl(cluster, "grp-a"));
Should.Throw<DbUpdateException>(() => db.SaveChanges());
}
/// <summary>Positive control: other principal, and the same principal in another cluster, are fine.</summary>
[Fact]
public void Cluster_scope_acls_for_other_principals_or_clusters_are_accepted()
{
var a = SeedCluster();
var b = SeedCluster();
using var db = NewContext();
db.NodeAcls.Add(ClusterAcl(a, "grp-a"));
db.NodeAcls.Add(ClusterAcl(a, "grp-b"));
db.NodeAcls.Add(ClusterAcl(b, "grp-a"));
Should.NotThrow(() => db.SaveChanges());
}
/// <summary>A stale ClusterNode write (token loaded before a concurrent edit) is refused, not last-writer-wins.</summary>
[Fact]
public void A_stale_cluster_node_edit_is_refused()
{
var cluster = SeedCluster();
var nodeId = Id("node") + ":4053";
using (var seed = NewContext())
{
seed.ClusterNodes.Add(new ClusterNode
{
NodeId = nodeId, ClusterId = cluster, Host = "h", ApplicationUri = "urn:" + Id("n"), CreatedBy = "t998",
});
seed.SaveChanges();
}
byte[] staleToken;
using (var form = NewContext()) staleToken = form.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).RowVersion;
staleToken.ShouldNotBeEmpty();
using (var other = NewContext())
{
var n = other.ClusterNodes.Single(x => x.NodeId == nodeId);
n.Enabled = false;
other.SaveChanges();
}
using var stale = NewContext();
var entity = stale.ClusterNodes.Single(x => x.NodeId == nodeId);
stale.Entry(entity).Property(e => e.RowVersion).OriginalValue = staleToken;
entity.Host = "changed";
Should.Throw<DbUpdateConcurrencyException>(() => stale.SaveChanges());
}
/// <summary>The same for ServerCluster; positive control: a write with the CURRENT token succeeds.</summary>
[Fact]
public void A_stale_server_cluster_edit_is_refused_but_a_current_one_succeeds()
{
var cluster = SeedCluster();
byte[] staleToken;
using (var form = NewContext()) staleToken = form.ServerClusters.AsNoTracking().Single(c => c.ClusterId == cluster).RowVersion;
using (var other = NewContext())
{
other.ServerClusters.Single(c => c.ClusterId == cluster).Notes = "concurrent";
other.SaveChanges();
}
using (var stale = NewContext())
{
var entity = stale.ServerClusters.Single(c => c.ClusterId == cluster);
stale.Entry(entity).Property(e => e.RowVersion).OriginalValue = staleToken;
entity.Notes = "stale";
Should.Throw<DbUpdateConcurrencyException>(() => stale.SaveChanges());
}
using var current = NewContext();
var fresh = current.ServerClusters.Single(c => c.ClusterId == cluster);
current.Entry(fresh).Property(e => e.RowVersion).OriginalValue = fresh.RowVersion;
fresh.Notes = "current";
Should.NotThrow(() => current.SaveChanges());
}
}
@@ -0,0 +1,241 @@
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#998 (review 2026-12-02 03-configuration C-3, C-5, C-10) — the deploy-gate rules that make the
/// draft the one authority: ZTag/SAPID duplicates, duplicate historian tagnames, and dangling logical FKs.
/// </summary>
[Trait("Category", "Unit")]
public sealed class DraftValidatorConfigurationGapsTests
{
private static DriverInstance Driver(string id = "drv-1", string cluster = "c1") => new()
{
DriverInstanceId = id, ClusterId = cluster, Name = "drv-" + id, DriverType = "Modbus", DriverConfig = "{}",
};
private static Device Dev(string id = "dev-1", string driver = "drv-1") => new()
{
DeviceId = id, DriverInstanceId = driver, Name = "dev-" + id, DeviceConfig = "{}",
};
private static Tag HistTag(string id, string name, string? tagname = null, bool readOnly = false,
string device = "dev-1", bool historized = true)
{
var cfg = new List<string>();
if (historized) cfg.Add("\"isHistorized\":true");
if (tagname is not null) cfg.Add($"\"historianTagname\":\"{tagname}\"");
if (readOnly) cfg.Add("\"historianReadOnly\":true");
return new Tag
{
TagId = id, DeviceId = device, Name = name, DataType = "Float",
AccessLevel = TagAccessLevel.Read, TagConfig = "{" + string.Join(",", cfg) + "}",
};
}
private static Guid UuidOf(string key) => new(System.Security.Cryptography.MD5.HashData(System.Text.Encoding.UTF8.GetBytes(key)));
/// <summary>The canonical (derived) EquipmentId for <paramref name="key"/>; the validator rejects any other id.</summary>
private static string Id(string key) => DraftValidator.DeriveEquipmentId(UuidOf(key));
private static Equipment Eq(string key, string? ztag = null, string? sap = null) => new()
{
EquipmentUuid = UuidOf(key), EquipmentId = Id(key), Name = "eq-" + key.ToLowerInvariant(), UnsLineId = "line-1",
MachineCode = "m-" + key, ZTag = ztag, SAPID = sap,
};
private static DraftSnapshot Snap(
IReadOnlyList<Tag>? tags = null, IReadOnlyList<Equipment>? equipment = null,
IReadOnlyList<DriverInstance>? drivers = null, IReadOnlyList<Device>? devices = null) => new()
{
GenerationId = 1, ClusterId = "c1",
UnsAreas = [new UnsArea { UnsAreaId = "area-1", ClusterId = "c1", Name = "area" }],
UnsLines = [new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line" }],
DriverInstances = drivers ?? [Driver()],
Devices = devices ?? [Dev()],
Tags = tags ?? [],
Equipment = equipment ?? [],
};
// ----- C-3: ZTag / SAPID uniqueness -----
/// <summary>Two equipment rows with the same ZTag (no reservation rows at all, as in production) are both named.</summary>
[Fact]
public void Duplicate_ztag_is_rejected_without_any_reservation_rows()
{
var errors = DraftValidator.Validate(Snap(equipment: [Eq("a", ztag: "ZT-001"), Eq("b", ztag: "zt-001 ")]));
var dup = errors.Where(e => e.Code == DraftValidator.DuplicateExternalIdentifierCode).ToList();
dup.Count.ShouldBe(2);
dup.Select(e => e.Context).ShouldBe([Id("a"), Id("b")], ignoreOrder: true);
dup[0].Message.ShouldContain("ZTag");
}
/// <summary>The same rule covers SAPID.</summary>
[Fact]
public void Duplicate_sapid_is_rejected()
{
var errors = DraftValidator.Validate(Snap(equipment: [Eq("a", sap: "S1"), Eq("b", sap: "S1")]));
errors.Count(e => e.Code == DraftValidator.DuplicateExternalIdentifierCode).ShouldBe(2);
}
/// <summary>Positive control: distinct values, repeated nulls and blanks, and a ZTag equal to another row's SAPID are all fine.</summary>
[Fact]
public void Distinct_null_and_blank_external_ids_are_accepted()
{
var errors = DraftValidator.Validate(Snap(equipment:
[
Eq("a", ztag: "ZT-1", sap: "X"), Eq("b", ztag: "ZT-2", sap: "Y"),
Eq("c"), Eq("d"), Eq("e", ztag: " ", sap: ""), Eq("f", ztag: "", sap: " "),
Eq("g", ztag: "X"),
]));
errors.ShouldNotContain(e => e.Code == DraftValidator.DuplicateExternalIdentifierCode);
}
// ----- C-5: historian tagname duplicates -----
/// <summary>A copied override: two owned historized tags with the same override are both named.</summary>
[Fact]
public void Two_owned_tags_with_the_same_historian_override_are_rejected()
{
var errors = DraftValidator.Validate(Snap(tags:
[
HistTag("t1", "speed", "Plant.Speed"), HistTag("t2", "speed2", "plant.speed"),
]));
var dup = errors.Where(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode).ToList();
dup.Select(e => e.Context).ShouldBe(["t1", "t2"], ignoreOrder: true);
}
/// <summary>An override equal to another tag's computed RawPath is the same collision.</summary>
[Fact]
public void An_override_equal_to_another_tags_rawpath_is_rejected()
{
// t1's RawPath = drv-drv-1/dev-dev-1/speed (no RawFolder); t2 overrides to exactly that.
var errors = DraftValidator.Validate(Snap(tags:
[
HistTag("t1", "speed"), HistTag("t2", "other", "drv-drv-1/dev-dev-1/speed"),
]));
errors.Count(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode).ShouldBe(2);
}
/// <summary>Positive controls: distinct names, a non-historized twin, and a historianReadOnly twin (decision: read-only sharing allowed).</summary>
[Fact]
public void Distinct_non_historized_and_read_only_twins_are_accepted()
{
var errors = DraftValidator.Validate(Snap(tags:
[
HistTag("t1", "a", "Plant.A"), HistTag("t2", "b", "Plant.B"),
HistTag("t3", "c", "Plant.A", historized: false),
HistTag("t4", "d", "Plant.A", readOnly: true),
HistTag("t5", "e", "Plant.RO", readOnly: true), HistTag("t6", "f", "Plant.RO", readOnly: true),
]));
errors.ShouldNotContain(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode);
}
/// <summary>The same override in two clusters is not provably a collision (separate historians): accepted.</summary>
[Fact]
public void The_same_override_in_different_clusters_is_accepted()
{
var errors = DraftValidator.Validate(Snap(
drivers: [Driver("drv-1", "c1"), Driver("drv-2", "c2")],
devices: [Dev("dev-1", "drv-1"), Dev("dev-2", "drv-2")],
tags: [HistTag("t1", "a", "Plant.A"), HistTag("t2", "a", "Plant.A", device: "dev-2")]));
errors.ShouldNotContain(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode);
}
// ----- C-10: dangling references -----
/// <summary>The orphan scenario: a tag whose Device was deleted concurrently is named, not silently skipped.</summary>
[Fact]
public void A_tag_under_a_deleted_device_is_rejected()
{
var errors = DraftValidator.Validate(Snap(tags: [HistTag("t1", "a", historized: false, device: "dev-gone")]));
var e = errors.ShouldHaveSingleItem();
e.Code.ShouldBe(DraftValidator.DanglingReferenceCode);
e.Context.ShouldBe("t1");
e.Message.ShouldContain("dev-gone");
}
/// <summary>Positive control: a complete, consistent graph (every link present) produces no error at all.</summary>
[Fact]
public void A_consistent_graph_has_no_dangling_reference()
{
var errors = DraftValidator.Validate(Snap(
tags: [HistTag("t1", "a", historized: false)],
equipment: [Eq("a")]));
errors.ShouldBeEmpty();
}
/// <summary>One case per logical link.</summary>
[Theory]
[InlineData("tag-group")]
[InlineData("tag-device")]
[InlineData("taggroup-device")]
[InlineData("taggroup-parent")]
[InlineData("device-driver")]
[InlineData("driver-folder")]
[InlineData("folder-parent")]
[InlineData("line-area")]
[InlineData("equipment-line")]
[InlineData("ref-tag")]
[InlineData("ref-equipment")]
[InlineData("vtag-equipment")]
[InlineData("alarm-equipment")]
public void Every_logical_parent_link_is_checked(string link)
{
var tag = HistTag("t1", "a", historized: false);
var snap = link switch
{
"tag-group" => Snap(tags: [Mutate(tag, t => t.TagGroupId = "g-gone")]),
"tag-device" => Snap(tags: [Mutate(tag, t => t.DeviceId = "dev-gone")]),
"taggroup-device" => With(Snap(tags: [tag]), tagGroups: [new TagGroup { TagGroupId = "g1", DeviceId = "dev-gone", Name = "g" }]),
"taggroup-parent" => With(Snap(tags: [tag]), tagGroups: [new TagGroup { TagGroupId = "g1", DeviceId = "dev-1", ParentTagGroupId = "g-gone", Name = "g" }]),
"device-driver" => Snap(tags: [tag], devices: [Dev("dev-1", "drv-gone")]),
"driver-folder" => Snap(tags: [tag], drivers: [Mutate(Driver(), d => d.RawFolderId = "f-gone")]),
"folder-parent" => With(Snap(tags: [tag]), rawFolders: [new RawFolder { RawFolderId = "f1", ClusterId = "c1", ParentRawFolderId = "f-gone", Name = "f" }]),
"line-area" => Snap(tags: [tag]),
"equipment-line" => Snap(tags: [tag], equipment: [Mutate(Eq("a"), e => e.UnsLineId = "line-gone")]),
"ref-tag" => With(Snap(tags: [tag], equipment: [Eq("a")]), refs: [new UnsTagReference { UnsTagReferenceId = "r1", EquipmentId = Id("a"), TagId = "t-gone" }]),
"ref-equipment" => With(Snap(tags: [tag], equipment: [Eq("a")]), refs: [new UnsTagReference { UnsTagReferenceId = "r1", EquipmentId = "EQ-gone", TagId = "t1" }]),
"vtag-equipment" => With(Snap(tags: [tag]), vtags: [new VirtualTag { VirtualTagId = "v1", EquipmentId = "EQ-gone", Name = "v", DataType = "Double", ScriptId = "s1", ChangeTriggered = true }], scripts: [Script("s1")]),
"alarm-equipment" => With(Snap(tags: [tag]), alarms: [new ScriptedAlarm { ScriptedAlarmId = "a1", EquipmentId = "EQ-gone", Name = "al", AlarmType = "LimitAlarm", MessageTemplate = "m", PredicateScriptId = "s1" }], scripts: [Script("s1")]),
_ => throw new ArgumentOutOfRangeException(nameof(link)),
};
if (link == "line-area")
snap = new DraftSnapshot
{
GenerationId = 1, ClusterId = "c1", UnsLines = [new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-gone", Name = "line" }],
};
var errors = DraftValidator.Validate(snap).Where(e => e.Code == DraftValidator.DanglingReferenceCode).ToList();
errors.ShouldHaveSingleItem();
}
private static T Mutate<T>(T row, Action<T> change) { change(row); return row; }
private static Script Script(string id) => new() { ScriptId = id, Name = id, SourceCode = "return 1;", SourceHash = "h" };
private static DraftSnapshot With(DraftSnapshot s, IReadOnlyList<TagGroup>? tagGroups = null, IReadOnlyList<RawFolder>? rawFolders = null,
IReadOnlyList<UnsTagReference>? refs = null, IReadOnlyList<VirtualTag>? vtags = null,
IReadOnlyList<ScriptedAlarm>? alarms = null, IReadOnlyList<Script>? scripts = null) => new()
{
GenerationId = s.GenerationId, ClusterId = s.ClusterId, UnsAreas = s.UnsAreas, UnsLines = s.UnsLines,
DriverInstances = s.DriverInstances, Devices = s.Devices, Tags = s.Tags, Equipment = s.Equipment,
TagGroups = tagGroups ?? s.TagGroups, RawFolders = rawFolders ?? s.RawFolders,
UnsTagReferences = refs ?? s.UnsTagReferences, VirtualTags = vtags ?? s.VirtualTags,
ScriptedAlarms = alarms ?? s.ScriptedAlarms, Scripts = scripts ?? s.Scripts,
};
}
@@ -51,24 +51,6 @@ public sealed class DraftValidatorTests
hasUnsError.ShouldBe(!shouldPass);
}
/// <summary>Verifies that equipment UUID must remain immutable across generations.</summary>
[Fact]
public void EquipmentUuid_change_across_generations_is_rejected()
{
var oldUuid = Guid.Parse("11111111-1111-1111-1111-111111111111");
var newUuid = Guid.Parse("22222222-2222-2222-2222-222222222222");
var eid = DraftValidator.DeriveEquipmentId(oldUuid);
var draft = new DraftSnapshot
{
GenerationId = 2, ClusterId = "c",
Equipment = [new Equipment { EquipmentUuid = newUuid, EquipmentId = eid, Name = "eq", UnsLineId = "line-a", MachineCode = "m" }],
PriorEquipment = [new Equipment { EquipmentUuid = oldUuid, EquipmentId = eid, Name = "eq", UnsLineId = "line-a", MachineCode = "m" }],
};
DraftValidator.Validate(draft).ShouldContain(e => e.Code == "EquipmentUuidImmutable");
}
/// <summary>Verifies that a ZTag cannot be reserved by a different equipment UUID.</summary>
[Fact]
public void ZTag_reserved_by_different_uuid_is_rejected()
@@ -489,77 +471,4 @@ public sealed class DraftValidatorTests
Enabled = enabled,
CreatedBy = "t",
};
// ------------------------------------------------------------------------------------
// ValidatePathLength — Enterprise/Site length precision (Configuration-003)
// ------------------------------------------------------------------------------------
/// <summary>Verifies that path length validation uses actual Enterprise and Site lengths.</summary>
[Fact]
public void PathLength_uses_actual_Enterprise_Site_when_provided()
{
var areaId = "area-a";
var lineId = "line-b";
var uuid = Guid.NewGuid();
var eqName = new string('x', 90); // 90 chars — exceeds UNS regex but that's a separate error
var snapshot = new DraftSnapshot
{
GenerationId = 1,
ClusterId = "c",
Enterprise = "zb", // 2 chars (actual)
Site = "s", // 1 char (actual)
UnsAreas = [new UnsArea { UnsAreaId = areaId, ClusterId = "c", Name = new string('a', 32) }],
UnsLines = [new UnsLine { UnsLineId = lineId, UnsAreaId = areaId, Name = new string('b', 32) }],
Equipment =
[
new Equipment
{
EquipmentUuid = uuid,
EquipmentId = DraftValidator.DeriveEquipmentId(uuid),
Name = eqName,
UnsLineId = lineId,
MachineCode = "m",
},
],
};
var errors = DraftValidator.Validate(snapshot);
errors.ShouldNotContain(e => e.Code == "PathTooLong",
"actual Enterprise='zb' + Site='s' keeps total path at 161 chars — under the 200-char limit");
}
/// <summary>Verifies that path length validation uses conservative fallback when Enterprise and Site are absent.</summary>
[Fact]
public void PathLength_conservative_fallback_when_Enterprise_Site_absent()
{
var areaId = "area-x";
var lineId = "line-y";
var uuid = Guid.NewGuid();
var snapshot = new DraftSnapshot
{
GenerationId = 1,
ClusterId = "c",
UnsAreas = [new UnsArea { UnsAreaId = areaId, ClusterId = "c", Name = new string('a', 32) }],
UnsLines = [new UnsLine { UnsLineId = lineId, UnsAreaId = areaId, Name = new string('b', 32) }],
Equipment =
[
new Equipment
{
EquipmentUuid = uuid,
EquipmentId = DraftValidator.DeriveEquipmentId(uuid),
Name = new string('c', 29),
UnsLineId = lineId,
MachineCode = "m",
},
],
};
var errors = DraftValidator.Validate(snapshot);
errors.ShouldNotContain(e => e.Code == "PathTooLong",
"conservative 32+32+32+32+29+4 = 161 chars is still under the 200-char limit");
}
}
@@ -16,6 +16,22 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
[Trait("Category", "Unit")]
public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
private static readonly Guid EqUuid = Guid.Parse("33333333-3333-3333-3333-333333333333");
private static readonly string EqId = DraftValidator.DeriveEquipmentId(EqUuid);
// The logical parents every row needs (DanglingReference, #998): one consistent Area/Line/Equipment + Driver/Device.
private static readonly Equipment Eq = new()
{
EquipmentUuid = EqUuid, EquipmentId = EqId, Name = "eq", UnsLineId = "line-1", MachineCode = "m",
};
private static readonly UnsLine Line = new() { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line" };
private static readonly UnsArea Area = new() { UnsAreaId = "area-1", ClusterId = "c", Name = "area" };
private static readonly DriverInstance Drv = new()
{
DriverInstanceId = "drv-1", ClusterId = "c", Name = "drv", DriverType = "Modbus", DriverConfig = "{}",
};
private static readonly Device Dev = new() { DeviceId = "dev-1", DriverInstanceId = "drv-1", Name = "dev", DeviceConfig = "{}" };
private static Script ScriptRow(string id) => new()
{
ScriptId = id, Name = id, SourceCode = "return 1;", SourceHash = "h-" + id,
@@ -23,13 +39,13 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
private static VirtualTag Vt(string name, string scriptId = "s1", string id = "vt-1") => new()
{
VirtualTagId = id, EquipmentId = "eq-1", Name = name, DataType = "Double", ScriptId = scriptId,
VirtualTagId = id, EquipmentId = EqId, Name = name, DataType = "Double", ScriptId = scriptId,
ChangeTriggered = true, TimerIntervalMs = 1000,
};
private static ScriptedAlarm Alarm(string predicateScriptId, bool enabled = true) => new()
{
ScriptedAlarmId = "al-1", EquipmentId = "eq-1", Name = "HighTemp", AlarmType = "LimitAlarm",
ScriptedAlarmId = "al-1", EquipmentId = EqId, Name = "HighTemp", AlarmType = "LimitAlarm",
MessageTemplate = "hot", PredicateScriptId = predicateScriptId, Enabled = enabled,
};
@@ -41,7 +57,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
private static UnsTagReference Ref(string? overrideName) => new()
{
UnsTagReferenceId = "ref-1", EquipmentId = "eq-1", TagId = "tag-1", DisplayNameOverride = overrideName,
UnsTagReferenceId = "ref-1", EquipmentId = EqId, TagId = "tag-1", DisplayNameOverride = overrideName,
};
// ----- C-1 / R-5: VirtualTag name -----
@@ -56,11 +72,11 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
public void An_illegal_virtual_tag_name_is_rejected(string name)
{
// Premise: this is exactly a name the runtime would throw on.
Should.Throw<ArgumentException>(() => V3NodeIds.Uns("eq-1", name));
Should.Throw<ArgumentException>(() => V3NodeIds.Uns(EqId, name));
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
});
errors.ShouldHaveSingleItem().Code.ShouldBe(DraftValidator.VirtualTagNameInvalidCode);
@@ -75,10 +91,10 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
[InlineData("_x")]
public void A_legal_virtual_tag_name_is_accepted(string name)
{
V3NodeIds.Uns("eq-1", name).ShouldBe("eq-1/" + name);
V3NodeIds.Uns(EqId, name).ShouldBe(EqId + "/" + name);
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
}).ShouldBeEmpty();
}
@@ -92,7 +108,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
});
var error = errors.ShouldHaveSingleItem();
@@ -109,7 +125,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
public void A_legal_or_absent_override_is_accepted(string? overrideName) =>
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
}).ShouldBeEmpty();
/// <summary>C-4 secondary: an EMPTY-string override means "use the raw tag name" at both compose seams, so
@@ -120,7 +136,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev],
Tags = [RawTag("speed")],
UnsTagReferences = [Ref("")],
VirtualTags = [Vt("speed")],
@@ -142,7 +158,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
};
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev],
Tags = [RawTag("speed")],
UnsTagReferences = [Ref("")],
VirtualTags = [Vt("computed")],
@@ -161,7 +177,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", VirtualTags = [Vt("computed", scriptId: "s-gone")], Scripts = [ScriptRow("s1")],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], VirtualTags = [Vt("computed", scriptId: "s-gone")], Scripts = [ScriptRow("s1")],
});
var error = errors.ShouldHaveSingleItem();
@@ -177,7 +193,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", ScriptedAlarms = [Alarm("s-gone", enabled)], Scripts = [ScriptRow("s1")],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], ScriptedAlarms = [Alarm("s-gone", enabled)], Scripts = [ScriptRow("s1")],
});
var error = errors.ShouldHaveSingleItem();
@@ -191,7 +207,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
public void Rows_referencing_an_existing_script_are_accepted() =>
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev],
VirtualTags = [Vt("computed")],
ScriptedAlarms = [Alarm("s1")],
Scripts = [ScriptRow("s1")],
@@ -35,6 +35,25 @@ public sealed class LdapGroupRoleMappingServiceTests
saved.CreatedAtUtc.ShouldBeGreaterThan(DateTime.UtcNow.AddMinutes(-1));
}
/// <summary>#998 (C-8): a second system-wide row for one group is refused in words; a cluster row, another group and another cluster are not.</summary>
[Fact]
public async Task Create_Rejects_A_Second_Row_For_The_Same_Group_And_Cluster_Bucket()
{
var svc = new LdapGroupRoleMappingService(_db);
await svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Administrator), CancellationToken.None);
var ex = await Should.ThrowAsync<InvalidLdapGroupRoleMappingException>(
() => svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Designer), CancellationToken.None));
ex.Message.ShouldContain("system-wide");
// Positive controls: the check is per (group, cluster bucket), not per group.
await svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Designer, clusterId: "c1"), CancellationToken.None);
await svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Designer, clusterId: "c2"), CancellationToken.None);
await svc.CreateAsync(Make("cn=other,dc=x", AdminRole.Administrator), CancellationToken.None);
await Should.ThrowAsync<InvalidLdapGroupRoleMappingException>(
() => svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Administrator, clusterId: "c1"), CancellationToken.None));
}
/// <summary>Verifies that Create rejects empty LDAP group.</summary>
[Fact]
public async Task Create_Rejects_EmptyLdapGroup()