feat(grpc-data): A1 ConditionStateHub — bounded partitions, per-reader reset, snapshot_complete readiness, F5 diagnostic; wired to the node manager

This commit is contained in:
Joseph Doherty
2026-11-24 09:24:28 -05:00
parent 6836efaeb9
commit 923c2511a3
5 changed files with 368 additions and 1 deletions
@@ -228,6 +228,22 @@ public static class OtOpcUaTelemetry
Meter.CreateCounter<long>("otopcua.opcua.standby.suppressed_alarm_events", unit: "{event}",
description: "New alarm condition events suppressed on a Warm standby.");
/// <summary>A1: driver instances whose initial alarm state was not signalled within their
/// <c>DataConnections:ConditionKnownSignalTimeout</c> (their conditions stay unknown, never known-inactive).</summary>
public static readonly Counter<long> DataConnConditionsUnsignalled =
Meter.CreateCounter<long>("otopcua.dataconn.conditions.unsignalled", unit: "{condition}",
description: "Native conditions whose initial alarm state was not signalled within the signal timeout.");
/// <summary>A1: condition-state hub partitions whose bounded buffer overflowed (epoch invalidated ⇒ subscribers resnapshot).</summary>
public static readonly Counter<long> DataConnConditionPartitionOverflows =
Meter.CreateCounter<long>("otopcua.dataconn.conditions.partition_overflows", unit: "{overflow}",
description: "Condition-state hub partition overflows (epoch invalidated).");
/// <summary>A1 (G3): deferred MarkConditionsKnown discarded because an alarm projection of the same source did not land.</summary>
public static readonly Counter<long> DataConnConditionMarksDiscarded =
Meter.CreateCounter<long>("otopcua.dataconn.conditions.marks_discarded", unit: "{mark}",
description: "Deferred condition-known marks discarded after a deferred alarm projection was dropped or skipped.");
// ---------------- Convenience helpers ----------------
/// <summary>
@@ -61,6 +61,8 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private readonly IProjectedBrowseAccess? _projectedBrowseAccess;
private readonly IProjectedDataAccess? _projectedDataAccess;
private readonly IProjectedHistoryAccess? _projectedHistoryAccess;
// A1 (plan §5.1): the condition-state hub the node manager's delta callback feeds. Invisible until A2.
private readonly IConditionStateSink? _conditionStateSink;
private readonly IFederatedProjectionCatalog? _projectedCatalog;
private readonly DataConnectionOptions _dataConnectionOptions;
@@ -167,9 +169,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
IProjectedBrowseAccess? projectedBrowseAccess = null,
IProjectedDataAccess? projectedDataAccess = null,
IFederatedProjectionCatalog? projectedCatalog = null,
IProjectedHistoryAccess? projectedHistoryAccess = null)
IProjectedHistoryAccess? projectedHistoryAccess = null,
IConditionStateSink? conditionStateSink = null)
{
_projectedHistoryAccess = projectedHistoryAccess;
_conditionStateSink = conditionStateSink;
_dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new();
_projectedBrowseAccess = projectedBrowseAccess;
_projectedDataAccess = projectedDataAccess;
@@ -269,6 +273,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_server.NodeManager.ProjectedBrowseClock = _time;
_server.NodeManager.ProjectedDataAccess = _projectedDataAccess;
_server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess;
_server.NodeManager.ConditionStateSink = _conditionStateSink;
if (_projectedCatalog is { } projectedCatalog)
_server.NodeManager.MappedSubjectResolver = (realm, identifier) =>
projectedCatalog.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns,
@@ -0,0 +1,203 @@
using System.Collections.Concurrent;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>
/// The origin's condition-state hub (plan §5.1, A1): the node manager's SDK-free delta callback lands here, in
/// bounded per-partition buffers, and A2's condition streams read from it. Header-gated and invisible until A2.
/// </summary>
/// <remarks>
/// <para>
/// <b>Never blocks the node manager.</b> <see cref="Append"/> and <see cref="Watermark"/> run under the node
/// manager's <c>Lock</c>: they take one partition's tiny lock, enqueue and return — no I/O, no wait. A full
/// partition evicts its oldest record and raises that partition's <b>floor</b>; a reader whose cursor sits below
/// the floor has lost a record and must reset to a fresh snapshot (<see cref="ConditionDeltaRead.ResetRequired"/>).
/// That is the plan's "partition epoch invalidated", made per reader so a caught-up reader is never reset.
/// </para>
/// <para>
/// <b>Versions are global.</b> One monotonically increasing version across partitions, so a snapshot slice's
/// watermark (taken under the same <c>Lock</c>) orders every delta for every condition in that slice.
/// </para>
/// <para>
/// <b><c>snapshot_complete</c> readiness</b> = the node manager's current apply has completed
/// (<see cref="OnApplyStateChanged"/>) AND this node holds its Primary verdict
/// (<see cref="IDriverPrimaryRoleSource.ShouldActAsPrimary"/>). Until both hold, A2 sends a Control <c>NotReady</c>.
/// </para>
/// <para>
/// <b>Unsignalled-state diagnostic (F5).</b> <see cref="ReportUnsignalled"/> records "initial alarm state not
/// signalled" per driver instance (elapsed time, condition count) and counts
/// <c>otopcua.dataconn.conditions.unsignalled</c>; a later signal clears it (<see cref="ClearUnsignalled"/>).
/// </para>
/// </remarks>
public sealed class ConditionStateHub : IConditionStateSink
{
/// <summary>Default partition count.</summary>
public const int DefaultPartitionCount = 16;
/// <summary>Default per-partition buffer capacity (records).</summary>
public const int DefaultPartitionCapacity = 8192;
private sealed class Partition
{
public readonly object Gate = new();
public readonly Queue<ConditionStateRecord> Buffer = new();
public long Floor;
}
private readonly Partition[] _partitions;
private readonly int _capacity;
private readonly IDriverPrimaryRoleSource? _primary;
private readonly ConcurrentDictionary<string, UnsignalledConditionState> _unsignalled = new(StringComparer.Ordinal);
private long _version;
private volatile bool _applyComplete;
/// <summary>Creates the hub.</summary>
/// <param name="primary">The node's Primary verdict, or null (never Primary ⇒ never snapshot-complete).</param>
/// <param name="partitionCount">Partition count (≥ 1).</param>
/// <param name="partitionCapacity">Records each partition retains (≥ 1).</param>
public ConditionStateHub(IDriverPrimaryRoleSource? primary = null, int partitionCount = DefaultPartitionCount,
int partitionCapacity = DefaultPartitionCapacity)
{
ArgumentOutOfRangeException.ThrowIfLessThan(partitionCount, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(partitionCapacity, 1);
_primary = primary;
_capacity = partitionCapacity;
_partitions = new Partition[partitionCount];
for (var i = 0; i < partitionCount; i++) _partitions[i] = new Partition();
}
/// <summary>The partition count.</summary>
public int PartitionCount => _partitions.Length;
/// <inheritdoc />
public long Watermark => Interlocked.Read(ref _version);
/// <summary>Whether the current address-space apply has completed.</summary>
public bool IsApplyComplete => _applyComplete;
/// <summary><c>snapshot_complete</c> may be sent: apply complete AND this node is Primary.</summary>
public bool IsSnapshotComplete => _applyComplete && _primary?.ShouldActAsPrimary == true;
/// <inheritdoc />
public long Append(ConditionStateRecord record)
{
ArgumentNullException.ThrowIfNull(record);
var p = _partitions[PartitionOf(record.Realm, record.ConditionId, _partitions.Length)];
lock (p.Gate)
{
// The version is taken inside the partition gate so each partition's buffer is in version order.
var version = Interlocked.Increment(ref _version);
if (p.Buffer.Count >= _capacity)
{
p.Floor = p.Buffer.Dequeue().Version;
OtOpcUaTelemetry.DataConnConditionPartitionOverflows.Add(1);
}
p.Buffer.Enqueue(record with { Version = version });
return version;
}
}
/// <inheritdoc />
public void OnApplyStateChanged(bool complete) => _applyComplete = complete;
/// <summary>The stable partition of a condition (FNV-1a over realm + id).</summary>
/// <param name="realm">The condition's realm.</param>
/// <param name="conditionId">The condition id.</param>
/// <param name="partitionCount">The partition count.</param>
/// <returns>The partition index.</returns>
public static int PartitionOf(AddressSpaceRealm realm, string conditionId, int partitionCount)
{
unchecked
{
var h = 2166136261u ^ (uint)realm;
h *= 16777619u;
foreach (var c in conditionId)
{
h = (h ^ c) * 16777619u;
}
return (int)(h % (uint)partitionCount);
}
}
/// <summary>
/// Read a partition's records with a version above <paramref name="afterVersion"/>, at most
/// <paramref name="max"/>. <see cref="ConditionDeltaRead.ResetRequired"/> when a record above the cursor was
/// already evicted — the reader must take a fresh snapshot of that partition.
/// </summary>
/// <param name="partition">The partition index.</param>
/// <param name="afterVersion">The reader's cursor (the slice watermark or the last version it applied).</param>
/// <param name="max">The most records to return.</param>
/// <returns>The read.</returns>
public ConditionDeltaRead Read(int partition, long afterVersion, int max = int.MaxValue)
{
var p = _partitions[partition];
lock (p.Gate)
{
if (afterVersion < p.Floor) return new ConditionDeltaRead(true, p.Floor, []);
var records = new List<ConditionStateRecord>();
foreach (var r in p.Buffer)
{
if (r.Version <= afterVersion) continue;
if (records.Count >= max) break;
records.Add(r);
}
return new ConditionDeltaRead(false, p.Floor, records);
}
}
/// <summary>Read every partition after one cursor (tests and diagnostics), in version order.</summary>
/// <param name="afterVersion">The cursor.</param>
/// <returns>The records, or null when any partition requires a reset.</returns>
public IReadOnlyList<ConditionStateRecord>? ReadAll(long afterVersion)
{
var all = new List<ConditionStateRecord>();
for (var i = 0; i < _partitions.Length; i++)
{
var read = Read(i, afterVersion);
if (read.ResetRequired) return null;
all.AddRange(read.Records);
}
all.Sort((a, b) => a.Version.CompareTo(b.Version));
return all;
}
/// <summary>F5: a driver's initial alarm state was not signalled in time — its conditions stay unknown.</summary>
/// <param name="driverInstanceId">The driver instance.</param>
/// <param name="elapsed">Time since its quality went Good.</param>
/// <param name="conditions">How many of its conditions are still unsignalled.</param>
public void ReportUnsignalled(string driverInstanceId, TimeSpan elapsed, int conditions)
{
ArgumentException.ThrowIfNullOrEmpty(driverInstanceId);
_unsignalled[driverInstanceId] = new UnsignalledConditionState(driverInstanceId, elapsed, conditions);
OtOpcUaTelemetry.DataConnConditionsUnsignalled.Add(conditions,
new KeyValuePair<string, object?>("driver", driverInstanceId));
}
/// <summary>A later signal (or the driver's removal) clears the diagnostic.</summary>
/// <param name="driverInstanceId">The driver instance.</param>
/// <returns>Whether a diagnostic was cleared.</returns>
public bool ClearUnsignalled(string driverInstanceId) => _unsignalled.TryRemove(driverInstanceId, out _);
/// <summary>The current "initial alarm state not signalled" diagnostics, by driver instance.</summary>
public IReadOnlyDictionary<string, UnsignalledConditionState> Unsignalled => _unsignalled;
}
/// <summary>One partition read.</summary>
/// <param name="ResetRequired">A record above the cursor was evicted; resnapshot the partition.</param>
/// <param name="Floor">The version of the last evicted record.</param>
/// <param name="Records">The records above the cursor, in version order.</param>
public sealed record ConditionDeltaRead(bool ResetRequired, long Floor, IReadOnlyList<ConditionStateRecord> Records);
/// <summary>The F5 data-connection diagnostic "initial alarm state not signalled".</summary>
/// <param name="DriverInstanceId">The driver instance.</param>
/// <param name="Elapsed">Time since its quality went Good when the timeout fired.</param>
/// <param name="Conditions">How many of its conditions were still unsignalled.</param>
public sealed record UnsignalledConditionState(string DriverInstanceId, TimeSpan Elapsed, int Conditions);
@@ -95,6 +95,12 @@ public static class ServiceCollectionExtensions
// publishes two verdicts into the same object rather than into two that disagree.
services.TryAddSingleton<RedundancyRoleView>();
services.TryAddSingleton<IDriverPrimaryRoleSource>(sp => sp.GetRequiredService<RedundancyRoleView>());
// A1 (grpc-data plan §5.1): the origin condition-state hub. The node manager's SDK-free delta callback feeds it;
// its snapshot_complete readiness reads the same Primary verdict. Header-gated and unread until A2.
services.TryAddSingleton(sp => new ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub(
sp.GetRequiredService<IDriverPrimaryRoleSource>()));
services.TryAddSingleton<ZB.MOM.WW.OtOpcUa.OpcUaServer.IConditionStateSink>(
sp => sp.GetRequiredService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub>());
// the continuous-historization capture verdict, registered here — unconditionally on
// every driver-role node — for the same reason as the line above, and NOT alongside the alarm
@@ -0,0 +1,137 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>A1 <see cref="ConditionStateHub"/>: bounded partitions, per-reader reset, readiness, F5 diagnostic.</summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "A1")]
[Trait("Category", "Unit")]
public sealed class ConditionStateHubTests : IDisposable
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-a1hub-{Guid.NewGuid():N}");
private static ConditionStateRecord Rec(string id, bool active = false, bool known = true) => new(
AddressSpaceRealm.Raw, id, true, 0, false, known, active, true, true, true, AlarmShelvingKind.Unshelved, 500, "m",
0, null, DateTime.UtcNow, active, new ConditionActivationMarker("i", 0));
private sealed class Primary(bool value) : IDriverPrimaryRoleSource
{
public bool ShouldActAsPrimary { get; set; } = value;
public void PublishPrimaryRole(bool shouldActAsPrimary) => ShouldActAsPrimary = shouldActAsPrimary;
}
[Fact]
public void Versions_are_global_and_reads_return_records_after_the_cursor()
{
var hub = new ConditionStateHub(partitionCount: 4);
var v1 = hub.Append(Rec("a"));
var v2 = hub.Append(Rec("b"));
v2.ShouldBe(v1 + 1);
hub.Watermark.ShouldBe(v2);
hub.ReadAll(0)!.Select(r => r.ConditionId).ShouldBe(["a", "b"]);
hub.ReadAll(v1)!.Single().ConditionId.ShouldBe("b");
}
[Fact]
public void An_overflow_resets_only_a_reader_that_fell_behind_the_evicted_record()
{
var hub = new ConditionStateHub(partitionCount: 1, partitionCapacity: 3);
for (var i = 0; i < 3; i++) hub.Append(Rec($"c{i}"));
var caughtUp = hub.Watermark;
hub.Append(Rec("c3")); // evicts version 1
hub.Read(0, afterVersion: 0).ResetRequired.ShouldBeTrue(); // lost record 1
hub.Read(0, afterVersion: 1).ResetRequired.ShouldBeFalse(); // record 1 already applied
hub.Read(0, caughtUp).Records.Single().ConditionId.ShouldBe("c3");
}
[Fact]
public void Snapshot_complete_needs_apply_complete_and_the_Primary_verdict()
{
var primary = new Primary(false);
var hub = new ConditionStateHub(primary);
hub.IsSnapshotComplete.ShouldBeFalse();
hub.OnApplyStateChanged(true);
hub.IsSnapshotComplete.ShouldBeFalse(); // not Primary
primary.ShouldActAsPrimary = true;
hub.IsSnapshotComplete.ShouldBeTrue();
hub.OnApplyStateChanged(false); // a rebuild began
hub.IsSnapshotComplete.ShouldBeFalse();
}
[Fact]
public void The_unsignalled_diagnostic_is_raised_and_cleared()
{
var hub = new ConditionStateHub();
hub.ReportUnsignalled("drv", TimeSpan.FromSeconds(120), 3);
hub.Unsignalled["drv"].Conditions.ShouldBe(3);
hub.ClearUnsignalled("drv").ShouldBeTrue();
hub.Unsignalled.ShouldBeEmpty();
}
/// <summary>
/// The falsely-empty negative test (A1): an origin restart with standing alarms. Until the apply completes the
/// hub is not snapshot-complete, and no record claims a condition known-inactive before its source projected.
/// </summary>
[Fact]
public async Task An_origin_restart_is_never_a_falsely_empty_or_falsely_normal_snapshot()
{
var primary = new Primary(true);
var hub = new ConditionStateHub(primary);
var (host, nm) = await BootAsync();
nm.ConditionStateSink = hub;
hub.IsSnapshotComplete.ShouldBeFalse(); // nothing applied yet: the cold node manager is not complete
nm.EnsureFolder("Plant/dev", null, "dev", AddressSpaceRealm.Raw);
nm.MaterialiseAlarmCondition("Plant/dev/A", "Plant/dev", "A", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
nm.MaterialiseAlarmCondition("Plant/dev/B", "Plant/dev", "B", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
hub.IsSnapshotComplete.ShouldBeFalse(); // mid-apply: the set may still be incomplete
nm.CompleteAddressSpaceApply();
hub.IsSnapshotComplete.ShouldBeTrue();
// A is a standing alarm whose replay has not arrived yet; nothing may say "known, inactive" about it.
hub.ReadAll(0)!.ShouldNotContain(r => r.StateKnown && !r.Active);
nm.WriteAlarmCondition("Plant/dev/A", new AlarmConditionSnapshot(true, false, true, true, AlarmShelvingKind.Unshelved, 700, "A"),
DateTime.UtcNow, AddressSpaceRealm.Raw);
nm.MarkConditionsKnown("drv", ["Plant/dev/A", "Plant/dev/B"], AddressSpaceRealm.Raw);
var records = hub.ReadAll(0)!;
records.Where(r => r.ConditionId == "Plant/dev/A" && r.StateKnown).ShouldAllBe(r => r.Active);
records.Last(r => r.ConditionId == "Plant/dev/B").StateKnown.ShouldBeTrue();
await host.DisposeAsync();
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaNodeManager Nm)> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(
port => new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.A1HubTest",
ApplicationUri = $"urn:OtOpcUa.A1HubTest:{Guid.NewGuid():N}",
OpcUaPort = port,
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
Microsoft.Extensions.Logging.Abstractions.NullLogger<OpcUaApplicationHost>.Instance),
() => new OtOpcUaSdkServer(), Ct);
return (started.Host, started.Server.NodeManager!);
}
/// <summary>Cleans up the PKI root directory.</summary>
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch { /* best-effort cleanup */ }
}
}
}