feat: preserve grpc write admission and uncertain outcomes

This commit is contained in:
Joseph Doherty
2026-11-16 03:56:13 -05:00
parent 8f28a0eabf
commit 862dbc8e90
37 changed files with 3686 additions and 70 deletions
@@ -0,0 +1,139 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P05")]
[Trait("Category", "Unit")]
public sealed class GrpcDataMappedWriteCompletionTests : IAsyncLifetime
{
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otua-mapped-write-{Guid.NewGuid():N}");
private OpcUaApplicationHost _host = null!;
private OtOpcUaSdkServer _server = null!;
private OtOpcUaNodeManager _manager = null!;
private EquipmentVariableState _node = null!;
private static readonly DateTime AuthoritativeTimestamp = new(2026, 10, 4, 12, 34, 56, DateTimeKind.Utc);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
public async ValueTask InitializeAsync()
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(
new OpcUaApplicationHostOptions { ApplicationName = "MappedWriteCompletion", ApplicationUri = $"urn:MappedWriteCompletion:{Guid.NewGuid():N}", PublicHostname = "localhost", OpcUaPort = port, PkiStoreRoot = _pki },
NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), Ct);
_host = started.Host;
_server = started.Server;
_manager = _server.NodeManager!;
_manager.EnsureVariable("v", null, "Value", "Int32", true, AddressSpaceRealm.Raw);
_manager.WriteValue("v", 7, OpcUaStatus.Good, AuthoritativeTimestamp, AddressSpaceRealm.Raw);
_node = (EquipmentVariableState)_manager.TryGetVariable("v", AddressSpaceRealm.Raw)!;
}
public async ValueTask DisposeAsync()
{
await _host.DisposeAsync();
if (Directory.Exists(_pki)) Directory.Delete(_pki, true);
}
[Theory]
[InlineData(DataWriteState.RejectedBeforeDispatch)]
[InlineData(DataWriteState.DriverConfirmedFailure)]
public async Task Definitive_failure_restores_authoritative_value(DataWriteState state)
{
var source = InstallWrite();
Write(42).ShouldBe(ServiceResult.Good);
SdkValueBoundary.ToClr(_node.Value).ShouldBe(42);
source.SetResult(new(state, StatusCodes.BadDeviceFailure.Code, "refused"));
await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct);
SdkValueBoundary.ToClr(_node.Value).ShouldBe(7);
_node.StatusCode.ShouldBe(StatusCodes.Good);
_node.Timestamp.ToDateTime().ShouldBe(AuthoritativeTimestamp);
}
[Theory]
[InlineData(DataWriteState.OutcomeUnknown)]
[InlineData(DataWriteState.AcceptedUnconfirmed)]
public async Task Ambiguous_outcomes_stay_uncertain_until_fresh_source_data(DataWriteState state)
{
var source = InstallWrite();
Write(42).ShouldBe(ServiceResult.Good);
source.SetResult(new(state, 0, null));
await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct);
_node.StatusCode.ShouldBe(StatusCodes.UncertainLastUsableValue);
SdkValueBoundary.ToClr(_node.Value).ShouldBe(7);
_node.Timestamp.ToDateTime().ShouldBe(AuthoritativeTimestamp);
_manager.WriteValue("v", 42, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw);
_node.StatusCode.ShouldBe(StatusCodes.Good);
}
[Fact]
public async Task Late_failure_cannot_overwrite_fresh_equal_valued_source_sample()
{
var source = InstallWrite();
Write(42).ShouldBe(ServiceResult.Good);
_manager.WriteValue("v", 42, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw);
source.SetResult(new(DataWriteState.DriverConfirmedFailure, 0, null));
await Task.Yield();
// The completion is synchronously testable through the manager's returned completion task.
await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct);
SdkValueBoundary.ToClr(_node.Value).ShouldBe(42);
_node.StatusCode.ShouldBe(StatusCodes.Good);
}
[Fact]
public async Task Older_failure_cannot_overwrite_newer_equal_valued_write()
{
var first = InstallWrite();
Write(42).ShouldBe(ServiceResult.Good);
var firstCompletion = _completion!;
var second = InstallWrite();
Write(42).ShouldBe(ServiceResult.Good);
first.SetResult(new(DataWriteState.DriverConfirmedFailure, 0, null));
await firstCompletion.WaitAsync(TimeSpan.FromSeconds(5), Ct);
SdkValueBoundary.ToClr(_node.Value).ShouldBe(42);
_node.StatusCode.ShouldBe(StatusCodes.Good);
second.SetResult(new(DataWriteState.DriverConfirmedSuccess, 0, null));
await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct);
}
[Fact]
public async Task Old_failure_cannot_overwrite_recreated_node_with_same_id_and_value()
{
var first = InstallWrite();
Write(42).ShouldBe(ServiceResult.Good);
var firstCompletion = _completion!;
_manager.RemoveVariableNode("v", AddressSpaceRealm.Raw).ShouldBeTrue();
_manager.EnsureVariable("v", null, "Replacement", "Int32", true, AddressSpaceRealm.Raw);
_manager.WriteValue("v", 42, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw);
var replacement = _manager.TryGetVariable("v", AddressSpaceRealm.Raw)!;
replacement.ShouldNotBeSameAs(_node);
first.SetResult(new(DataWriteState.DriverConfirmedFailure, 0, null));
await firstCompletion.WaitAsync(TimeSpan.FromSeconds(5), Ct);
SdkValueBoundary.ToClr(replacement.Value).ShouldBe(42);
replacement.StatusCode.ShouldBe(StatusCodes.Good);
}
private Task? _completion;
private TaskCompletionSource<DataWriteOutcome> InstallWrite()
{
var result = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
_node.OnWriteValue = (ISystemContext context, NodeState node, NumericRange range, QualifiedName encoding,
ref Variant value, ref StatusCode status, ref DateTimeUtc timestamp) =>
{
_completion = _manager.ObserveMappedWriteCompletion(result.Task, "v", AddressSpaceRealm.Raw,
SdkValueBoundary.ToClr(value), SdkValueBoundary.ToClr(_node.Value), _node.StatusCode,
_node.Timestamp.ToDateTime(), _node.ActiveWriteStamp!.Value);
return ServiceResult.Good;
};
return result;
}
private ServiceResult Write(int value) => _node.WriteAttribute(new ServerSystemContext(_server.CurrentInstance),
Attributes.Value, default, new Opc.Ua.DataValue(Variant.From(value)));
}
@@ -208,6 +208,63 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
old.IsActive.ShouldBeFalse();
}
[Fact]
[Trait("Phase", "P05")]
public async Task Coordinator_backed_source_callback_does_not_wait_for_role_refresh_fence()
{
var fence = new DataWriteDispatchFence();
var authority = new DataPlaneAuthorityState(fence);
var activation = new CatalogActivation(fence);
var liveServing = BootIdentity;
var coordinator = new LocalCatalogCoordinator(activation, authority, () => Volatile.Read(ref liveServing));
var attempt = Prepare(coordinator, Artifact());
coordinator.Complete(attempt, true).ShouldBeTrue();
coordinator.Current.ShouldNotBeNull().Serving.Role.ShouldBe("Primary");
using var hub = HubTest.Create(bytes: 1_000_000);
var publisher = new SourceSamplePublisher(hub, () => coordinator.Serving);
var producer = publisher.RegisterDriverIncarnation("driver");
publisher.RegisterDriverShape("driver", "ref", SourceValueShape.FromDriverType("Int32", false)).ShouldBeTrue();
publisher.EnsureDriverBinding("cluster", "driver", "ref", producer).ShouldBeTrue();
publisher.TryCaptureDriver("driver", "ref", producer, out var ticket).ShouldBeTrue();
var initialTime = new DateTime(2026, 11, 15, 8, 0, 0, DateTimeKind.Utc);
publisher.TryPublish(ticket, new DataValueSnapshot(1, OpcUaStatus.Good, initialTime, null)).ShouldBeTrue();
Volatile.Write(ref liveServing, BootIdentity with { Role = "Secondary" });
using var release = new ManualResetEventSlim();
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var holder = Task.Run(() =>
{
using (fence.Enter()) { held.TrySetResult(); release.Wait(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); }
}, TestContext.Current.CancellationToken);
await held.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var callback = Task.Run(() =>
{
started.TrySetResult();
return publisher.TryPublish(ticket, new DataValueSnapshot(2, OpcUaStatus.Good, initialTime.AddSeconds(1), null));
}, TestContext.Current.CancellationToken);
bool returnedBeforeRelease;
try
{
await started.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
returnedBeforeRelease = ReferenceEquals(await Task.WhenAny(callback,
Task.Delay(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken)), callback);
}
finally { release.Set(); }
await holder.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await callback.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
returnedBeforeRelease.ShouldBeTrue("a source callback must not wait for a dispatch-fence holder");
publisher.IsDriverIncarnationActive("driver", producer).ShouldBeTrue();
publisher.TryCaptureDriver("driver", "ref", producer, out var current).ShouldBeTrue();
var freshTime = initialTime.AddSeconds(2);
publisher.TryPublish(current, new DataValueSnapshot(3, OpcUaStatus.Good, freshTime, null)).ShouldBeTrue();
hub.ProcessPending();
using var fresh = hub.Read(current);
fresh.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(3);
fresh.Sample!.SourceTimestampUtc.ShouldBe(new DateTimeOffset(freshTime));
}
[Fact]
public void Host_and_publish_actor_join_one_attempt_and_wait_for_successful_topology()
{
@@ -0,0 +1,677 @@
using System.Collections.Immutable;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P05")]
public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
[Fact]
public async Task Revocation_after_actor_launch_but_before_the_invoker_delegate_prevents_the_device_call()
{
var driver = new RichDriver();
var gate = new RecordingGate();
var invoker = new PausedWriteInvoker();
var observer = new LateWriteObserver(2, TimeSpan.FromMinutes(1));
var actor = Connect(driver, gate, observer, invoker);
var (ticket, claim) = NewWrite("one", 1);
var response = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
await invoker.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
gate.Revoke();
invoker.Release.TrySetResult();
(await response.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
driver.Calls.ShouldBe(0);
claim.IsDispatched.ShouldBeFalse();
invoker.SawIdempotent.ShouldBeFalse("writes must not be retried");
}
[Theory]
[InlineData("unchanged")]
[InlineData("key-version")]
[InlineData("key-principal")]
[InlineData("expiry")]
[InlineData("remap")]
[InlineData("role")]
[InlineData("host-role-event")]
[InlineData("host-membership-event")]
[InlineData("incarnation")]
[InlineData("current-key-expiry-fence")]
public async Task Real_catalog_policy_and_actor_revalidate_at_the_driver_invocation(string change)
{
var clock = new PolicyCompletionClock();
var fence = new DataWriteDispatchFence();
var authority = new DataPlaneAuthorityState(fence);
var activation = new CatalogActivation(fence);
var role = new RedundancyRoleView(fence);
role.PublishPrimaryRole(true);
var serving = new ServingIdentity("node-a", "serving", "Primary", 0, 0);
var coordinator = new LocalCatalogCoordinator(activation, authority, () => serving);
var bytes = Encoding.UTF8.GetBytes("""
{
"Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}],
"Nodes":[{"NodeId":"node-a","ClusterId":"cluster","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}],
"ApiKeys":[{"ApiKeyId":"peer-key","Name":"peer-key","SecretHash":"hash","Principal":"peer","Enabled":true}],
"NodeAcls":[{"NodeAclId":"acl","ClusterId":"cluster","Principal":"peer","ScopeKind":0,"PermissionFlags":16}],
"RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}],
"DriverInstances":[{"DriverInstanceId":"driver","ClusterId":"cluster","RawFolderId":"folder","Name":"Driver","DriverType":"Modbus","DriverConfig":"{}","Enabled":true}],
"Devices":[{"DeviceId":"device","DriverInstanceId":"driver","Name":"Device","DeviceConfig":"{}","Enabled":true}],
"Tags":[{"TagId":"tag","DeviceId":"device","Name":"Speed","DataType":"Int32","AccessLevel":1,"TagConfig":"{}"}],
"TagGroups":[],"UnsAreas":[],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[],
"DataConnections":[],"RemoteNamespaceMappings":[],
"DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":8}]
}
""");
if (change == "current-key-expiry-fence")
{
var root = JsonNode.Parse(bytes)!.AsObject();
root["ApiKeys"]![0]!["ExpiresUtc"] = clock.GetUtcNow().AddSeconds(1).UtcDateTime.ToString("O");
bytes = Encoding.UTF8.GetBytes(root.ToJsonString());
}
var attempt = coordinator.BeginAttempt("catalog-revision");
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue();
using (var parsed = DeploymentArtifact.Open(bytes))
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!, "node-a").ShouldBeTrue();
coordinator.Complete(attempt, true).ShouldBeTrue();
var catalog = coordinator.Current.ShouldNotBeNull();
var node = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
node.Metadata.Writable.ShouldBeTrue();
var key = authority.Current.FindUsableKey("peer-key", clock.GetUtcNow().UtcDateTime).ShouldNotBeNull();
DateTimeOffset? callerExpiry = change == "current-key-expiry-fence" ? null
: clock.GetUtcNow() + (change == "expiry" ? TimeSpan.FromSeconds(1) : TimeSpan.FromMinutes(5));
var invoker = new PausedWriteInvoker();
var driver = new RichDriver();
var routes = new WriteRouteState(fence);
var policy = new DataOperationPolicy(authority,
new CompletionSignalingEvaluator(new TriePermissionEvaluator(authority.Tries, clock), clock), clock);
var gate = new DataWriteDispatchGate(coordinator, activation, authority, policy, role, routes, clock,
new DriverWriteBounds(TimeSpan.FromMilliseconds(100)));
BlockingHistorization? blockedHistorization = null;
BlockingHistoryUpdate? blockedHistoryUpdate = null;
IActorRef? roleHost = null;
var memberCount = 1;
if (change is "host-role-event" or "host-membership-event")
{
if (change == "host-role-event") blockedHistorization = new BlockingHistorization();
else blockedHistoryUpdate = new BlockingHistoryUpdate();
roleHost = Sys.ActorOf(DriverHostActor.Props(NewInMemoryDbFactory(),
ZB.MOM.WW.OtOpcUa.Commons.Types.NodeId.Parse("node-a"),
localRoles: new HashSet<string> { "driver" }, primaryRoleSource: role,
historizationRoleView: blockedHistorization, historyUpdateRoleView: blockedHistoryUpdate,
driverMemberCountProvider: () => Volatile.Read(ref memberCount)));
await roleHost.Ask<ActorIdentity>(new Identify("host-started"), Timeout, TestContext.Current.CancellationToken);
}
var actor = Connect(driver, gate, new LateWriteObserver(2, TimeSpan.FromMinutes(1), clock), invoker,
writeTimeout: TimeSpan.FromSeconds(10), writeClock: clock, writeRouteState: routes);
var incarnation = routes.CurrentDriverIncarnation("driver").ShouldNotBeNull();
var target = routes.Publish(node.Metadata.View, "driver", "Plant/Driver/Device/Speed", incarnation);
var now = clock.GetTimestamp();
var admission = new DataWriteAdmission("peer", node.Metadata.View, catalog.AuthorityEpoch,
catalog.Serving.CatalogEpoch, "serving", incarnation, "real-gate", now + 60 * clock.TimestampFrequency,
key.ApiKeyId, callerExpiry, DataCallerIdentity.CredentialVersionFor(key));
var proof = new WriteRouteProof(admission,
new(node.Scope.ClusterId, node.Scope.Kind, node.Scope.Segments.ToImmutableArray()),
node.EntityKind, node.EntityId, node.Source, "driver", target.DriverReference,
target.RouteGeneration, role.PrimaryGeneration);
var ticket = new WriteAdmissionTicket(proof, DataValue.FromScalar(DataValueKind.Int32, 7), now);
var registry = new WriteOperationRegistry("serving", 8, 8192, TimeSpan.FromMinutes(1), clock);
var claim = registry.Claim("peer", "real-gate", "serving", SHA256.HashData([1, 2, 3])).Claim.ShouldNotBeNull();
var response = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
await invoker.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
try
{
switch (change)
{
case "key-version":
case "key-principal":
authority.Apply("cluster", "changed", [new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Enabled = true,
Principal = change == "key-principal" ? "other" : "peer", SecretHash = change == "key-version" ? "replacement" : "hash" }],
[new NodeAcl { NodeAclId = "acl", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.Cluster,
PermissionFlags = NodePermissions.WriteOperate }], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
break;
case "expiry": clock.Advance(TimeSpan.FromSeconds(2)); break;
case "remap": routes.Publish(node.Metadata.View, "other", "other/path", "other-incarnation"); break;
case "role": role.PublishPrimaryRole(false); role.PublishPrimaryRole(true); break;
case "incarnation": routes.RetireDriver("driver", incarnation); routes.BeginDriverIncarnation("driver"); break;
case "current-key-expiry-fence":
{
using var releaseFence = new ManualResetEventSlim();
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var holder = Task.Run(() =>
{
using (fence.Enter()) { held.TrySetResult(); releaseFence.Wait(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); }
}, TestContext.Current.CancellationToken);
try
{
await held.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
invoker.Release.TrySetResult();
// The wrapped evaluator arms a signal for the *last* policy UTC read. It returns
// the captured pre-expiry instant even if the test advances the clock immediately.
await clock.AfterPolicyUtc.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
clock.Advance(TimeSpan.FromSeconds(2));
}
finally { releaseFence.Set(); await holder.WaitAsync(Timeout, TestContext.Current.CancellationToken); }
break;
}
case "host-role-event":
blockedHistorization!.Arm();
roleHost!.Tell(new RedundancyStateChanged([
new NodeRedundancyState(ZB.MOM.WW.OtOpcUa.Commons.Types.NodeId.Parse("node-a"), RedundancyRole.Secondary,
IsClusterLeader: false, IsDriverPrimary: false, AsOfUtc: DateTime.UtcNow)], CorrelationId.NewId()));
await blockedHistorization!.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
role.ShouldActAsPrimary.ShouldBeFalse("the write verdict must publish before the historian callback can block");
role.PrimaryGeneration.ShouldBeGreaterThan(proof.PrimaryGeneration);
break;
case "host-membership-event":
blockedHistoryUpdate!.Arm();
Volatile.Write(ref memberCount, 2);
roleHost!.Tell(new Akka.Cluster.ClusterEvent.MemberUp(Akka.Cluster.Cluster.Get(Sys).SelfMember));
await blockedHistoryUpdate.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
role.ShouldActAsPrimary.ShouldBeFalse("MemberUp must publish the write verdict before the history-update callback blocks");
role.PrimaryGeneration.ShouldBeGreaterThan(proof.PrimaryGeneration);
break;
}
invoker.Release.TrySetResult();
var outcome = await response.WaitAsync(Timeout, TestContext.Current.CancellationToken);
if (change == "unchanged")
{ outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); driver.Calls.ShouldBe(1); }
else
{ outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); driver.Calls.ShouldBe(0); claim.IsDispatched.ShouldBeFalse(); }
}
finally { blockedHistorization?.Release.Set(); blockedHistoryUpdate?.Release.Set(); invoker.Release.TrySetResult(); }
}
[Fact]
public async Task A_terminal_proven_no_call_claim_cannot_invoke_a_driver_after_its_ticket_is_released()
{
var driver = new RichDriver();
var invoker = new PausedWriteInvoker();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)), invoker);
var (ticket, claim) = NewWrite("no-call", 1);
var response = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
await invoker.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
claim.Complete(new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "deadline before dispatch")).ShouldBeTrue();
ticket.Dispose();
invoker.Release.TrySetResult();
(await response.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
claim.IsDispatched.ShouldBeFalse();
driver.Calls.ShouldBe(0);
}
[Fact]
public async Task Queued_write_revalidates_after_an_earlier_write_finishes()
{
var driver = new RichDriver { Hold = true };
var gate = new RecordingGate();
var observer = new LateWriteObserver(2, TimeSpan.FromMinutes(1));
var actor = Connect(driver, gate, observer, maxWrites: 1);
var (firstTicket, firstClaim) = NewWrite("first", 1);
var first = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(firstTicket, firstClaim), Timeout, TestContext.Current.CancellationToken);
await driver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
var (secondTicket, secondClaim) = NewWrite("second", 2);
var probe = CreateTestProbe();
probe.Send(actor, new DriverInstanceActor.WriteAttributeWithOutcome(secondTicket, secondClaim));
probe.Send(actor, new Identify("queue-barrier"));
probe.ExpectMsg<ActorIdentity>(Timeout, cancellationToken: TestContext.Current.CancellationToken);
gate.Revoke();
driver.Release.TrySetResult();
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
probe.ExpectMsg<DataWriteOutcome>(Timeout, cancellationToken: TestContext.Current.CancellationToken).State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
driver.Calls.ShouldBe(1);
secondClaim.IsDispatched.ShouldBeFalse();
}
[Fact]
public async Task Legacy_good_without_an_explicit_completion_guarantee_is_unconfirmed()
{
var driver = new LegacyDriver();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (ticket, claim) = NewWrite("legacy", 1);
var result = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
driver.Calls.ShouldBe(1);
}
[Fact]
public async Task Token_ignoring_driver_stays_charged_and_its_actual_late_success_refines_unknown()
{
var driver = new RichDriver { Hold = true };
var observer = new LateWriteObserver(1, TimeSpan.FromMinutes(1));
var actor = Connect(driver, new RecordingGate(), observer, maxWrites: 1,
writeTimeout: TimeSpan.FromMilliseconds(200));
var (ticket, claim) = NewWrite("hung", 1);
var first = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
await driver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
// The actor has abandoned its wait, but the actual token-ignoring driver is still alive.
// A second operation cannot escape the separate physical outstanding-call limit.
var (secondTicket, secondClaim) = NewWrite("capacity", 2);
var second = await actor.Ask<DataWriteOutcome>(
new DriverInstanceActor.WriteAttributeWithOutcome(secondTicket, secondClaim), Timeout, TestContext.Current.CancellationToken);
second.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
secondClaim.IsDispatched.ShouldBeFalse();
driver.Calls.ShouldBe(1);
driver.Release.TrySetResult();
AwaitCondition(() => claim.CurrentOutcome?.State == DataWriteState.DriverConfirmedSuccess, Timeout, TestContext.Current.CancellationToken);
driver.Calls.ShouldBe(1);
}
[Fact]
public async Task Timed_out_physical_write_rejects_the_same_target_while_a_different_target_progresses()
{
var driver = new RichDriver { Hold = true, HoldFirstOnly = true };
// The observation window expires before abandonment; physical ownership must still remain.
var observer = new LateWriteObserver(2, TimeSpan.FromMilliseconds(50));
var actor = Connect(driver, new RecordingGate(), observer, maxWrites: 1,
writeTimeout: TimeSpan.FromMilliseconds(200));
var (firstTicket, firstClaim) = NewWrite("held", 1, "plant/tag-a");
try
{
var first = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(firstTicket, firstClaim),
Timeout, TestContext.Current.CancellationToken);
await driver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
var (sameTicket, sameClaim) = NewWrite("same", 2, "plant/tag-a");
var same = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(sameTicket, sameClaim),
Timeout, TestContext.Current.CancellationToken);
same.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
sameClaim.IsDispatched.ShouldBeFalse();
driver.Calls.ShouldBe(1, "the first physical write still owns this canonical target");
var (otherTicket, otherClaim) = NewWrite("other", 3, "plant/tag-b");
var other = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(otherTicket, otherClaim),
Timeout, TestContext.Current.CancellationToken);
other.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
driver.Calls.ShouldBe(2);
}
finally { driver.Release.TrySetResult(); }
}
[Fact]
public async Task Replacement_actor_cannot_write_a_target_still_held_by_the_previous_actor()
{
var observer = new LateWriteObserver(2, TimeSpan.FromMinutes(1));
var oldDriver = new RichDriver { Hold = true, HoldFirstOnly = true };
var oldActor = Connect(oldDriver, new RecordingGate(), observer, maxWrites: 1,
writeTimeout: TimeSpan.FromMilliseconds(200));
var (oldTicket, oldClaim) = NewWrite("old", 1, "plant/tag-a");
try
{
var first = oldActor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(oldTicket, oldClaim),
Timeout, TestContext.Current.CancellationToken);
await oldDriver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
Watch(oldActor);
Sys.Stop(oldActor);
ExpectTerminated(oldActor, Timeout, cancellationToken: TestContext.Current.CancellationToken);
var replacementDriver = new RichDriver { DriverInstanceId = "DRIVER" };
var replacement = Connect(replacementDriver, new RecordingGate(), observer, maxWrites: 1);
var (sameTicket, sameClaim) = NewWrite("replacement-same", 2, "plant/tag-a", "DRIVER");
var same = await replacement.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(sameTicket, sameClaim),
Timeout, TestContext.Current.CancellationToken);
same.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
sameClaim.IsDispatched.ShouldBeFalse();
replacementDriver.Calls.ShouldBe(0);
var (otherTicket, otherClaim) = NewWrite("replacement-other", 3, "plant/tag-b", "DRIVER");
var other = await replacement.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(otherTicket, otherClaim),
Timeout, TestContext.Current.CancellationToken);
other.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
oldDriver.Release.TrySetResult();
AwaitCondition(() => oldClaim.CurrentOutcome?.State == DataWriteState.DriverConfirmedSuccess,
Timeout, cancellationToken: TestContext.Current.CancellationToken);
DataWriteOutcome? after = null;
for (var i = 0; i < 100; i++)
{
var (retryTicket, retryClaim) = NewWrite($"after-{i}", 4, "plant/tag-a", "DRIVER");
after = await replacement.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(retryTicket, retryClaim),
Timeout, TestContext.Current.CancellationToken);
if (after.State == DataWriteState.DriverConfirmedSuccess) break;
after.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
await Task.Delay(10, TestContext.Current.CancellationToken);
}
after.ShouldNotBeNull().State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
replacementDriver.Calls.ShouldBe(2, "only the other target and the post-completion write reached the device");
}
finally { oldDriver.Release.TrySetResult(); }
}
[Fact]
public async Task Synchronous_driver_throw_after_dispatch_is_unknown()
{
var driver = new SynchronousThrowDriver();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (ticket, claim) = NewWrite("throw", 1);
var outcome = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
claim.IsDispatched.ShouldBeTrue();
driver.Calls.ShouldBe(1);
}
[Fact]
public async Task A_driver_blocking_before_returning_its_task_remains_physically_charged()
{
using var release = new ManualResetEventSlim();
var driver = new SynchronousBlockingDriver(release);
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)),
maxWrites: 1, writeTimeout: TimeSpan.FromMilliseconds(200));
var (ticket, claim) = NewWrite("blocking", 1);
var first = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
try
{
await driver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
var (laterTicket, laterClaim) = NewWrite("later", 2);
var later = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(laterTicket, laterClaim), Timeout, TestContext.Current.CancellationToken);
later.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
laterClaim.IsDispatched.ShouldBeFalse();
driver.Calls.ShouldBe(1);
}
finally { release.Set(); }
}
[Fact]
public void Supervision_restart_fences_the_old_driver_incarnation_even_when_the_actor_ref_is_reused()
{
var driver = new RichDriver();
var routes = new WriteRouteState(new DataWriteDispatchFence());
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.PropsForRichWrites(driver, commsLossTimeout: TimeSpan.Zero,
writeRouteState: routes), new OneForOneStrategy(_ => Directive.Restart), TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, Timeout, cancellationToken: TestContext.Current.CancellationToken);
var incarnation = routes.CurrentDriverIncarnation("driver");
incarnation.ShouldNotBeNullOrWhiteSpace();
var view = new DataView(new("cluster", "urn:raw", "string", "plant/tag"), DataRealm.Raw, null, 0, "plant/tag");
var oldRoute = routes.Publish(view, "driver", "plant/tag", incarnation!);
routes.IsCurrent(view, oldRoute).ShouldBeTrue();
// Restart in place: the same IActorRef addresses a new actor object around the same driver object.
actor.Tell(Kill.Instance);
parent.FishForMessage(m => m is DriverInstanceActor.ReprovisionRequested, Timeout,
cancellationToken: TestContext.Current.CancellationToken);
var replacement = routes.CurrentDriverIncarnation("driver");
replacement.ShouldNotBe(incarnation);
routes.IsCurrent(view, oldRoute).ShouldBeFalse();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Host_retires_the_write_incarnation_before_stopping_a_child(bool operatorRestart)
{
var db = NewInMemoryDbFactory();
var firstRev = RevisionHash.Parse(new string('a', 64));
var secondRev = RevisionHash.Parse(new string('b', 64));
var raw = new[] { ("driver", "Modbus", "dev1", "speed", "Int32", true) };
var first = V3ArtifactSeeder.SeedV3Deployment(db, firstRev, raw, [], enabled: true);
var second = V3ArtifactSeeder.SeedV3Deployment(db, secondRev, raw, [], enabled: false);
var node = ZB.MOM.WW.OtOpcUa.Commons.Types.NodeId.Parse("node-1:4053");
var fence = new DataWriteDispatchFence();
var authority = new DataPlaneAuthorityState(fence);
var activation = new CatalogActivation(fence);
var role = new RedundancyRoleView(fence);
var clock = TimeProvider.System;
var serving = new ServingIdentity(node.Value, "serving", "Primary", 0, 0);
var catalog = new LocalCatalogCoordinator(activation, authority, () => serving);
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilitiesProvider("c1", () => catalog.Serving, () => catalog.Current is not null, limits);
var bounds = new DriverWriteBounds(TimeSpan.FromMilliseconds(300));
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, clock), clock);
var runtime = new DataWriteRuntime(catalog, activation, authority, policy, capabilities, role, clock, bounds,
"serving", 16, 16_384, 16_384, 4, TimeSpan.FromMinutes(1));
var driver = new RichDriver();
var stopped = new TaskCompletionSource<(string? Incarnation, int Shutdowns)>(TaskCreationOptions.RunContinuationsAsynchronously);
runtime.BeforeDriverStopForTests = id => stopped.TrySetResult((runtime.Routes.CurrentDriverIncarnation(id), driver.Shutdowns));
var acks = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(db, node, acks.Ref, driverFactory: new SingleDriverFactory(driver),
localRoles: new HashSet<string> { "driver" }, primaryRoleSource: role, catalogCoordinator: catalog,
writeBounds: bounds, writeClock: clock, dataWriteRuntime: runtime));
host.Tell(new DispatchDeployment(first, firstRev, CorrelationId.NewId()));
acks.ExpectMsg<ApplyAck>(Timeout, cancellationToken: TestContext.Current.CancellationToken);
AwaitCondition(() => runtime.Routes.CurrentDriverIncarnation("driver") is not null, Timeout, TestContext.Current.CancellationToken);
if (operatorRestart) host.Tell(new RestartDriver("c1", "driver", "tester", Guid.NewGuid()));
else host.Tell(new DispatchDeployment(second, secondRev, CorrelationId.NewId()));
var observed = await stopped.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
observed.Shutdowns.ShouldBe(0, "the child has not yet run PostStop");
observed.Incarnation.ShouldBeNull("host retirement must precede the asynchronous child stop");
}
[Fact]
public async Task Gateway_timeout_uses_the_injected_write_clock_and_proves_no_call_before_rejection()
{
var clock = new ManualTimeProvider();
var bounds = new DriverWriteBounds(TimeSpan.FromMilliseconds(100));
var role = new RedundancyRoleView(new DataWriteDispatchFence());
var routes = new WriteRouteState(role.DispatchFence);
var host = CreateTestProbe();
var route = new ActorDataWriteRoute(() => host.Ref, routes, role, bounds, clock);
var (ticket, claim) = NewWrite("gateway-timeout", 1);
var pending = route.DispatchAsync(ticket, claim, CancellationToken.None);
host.ExpectMsg<DriverHostActor.RouteRichWrite>(Timeout, cancellationToken: TestContext.Current.CancellationToken);
await clock.WaitForTimerDueAtAsync(clock.Start + bounds.GatewayAsk, Timeout);
pending.IsCompleted.ShouldBeFalse();
clock.Advance(bounds.GatewayAsk);
(await pending.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
claim.IsDispatched.ShouldBeFalse();
}
private IActorRef Connect(IDriver driver, IWriteDispatchGate gate, LateWriteObserver observer,
IDriverCapabilityInvoker? invoker = null, int maxWrites = 4, TimeSpan? writeTimeout = null,
TimeProvider? writeClock = null, WriteRouteState? writeRouteState = null)
{
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.PropsForRichWrites(driver, invoker: invoker,
commsLossTimeout: TimeSpan.Zero, maxWritesInFlight: maxWrites,
writeTimeout: writeTimeout ?? Timeout, writeDispatchGate: gate, lateWriteObserver: observer,
writeClock: writeClock, writeRouteState: writeRouteState));
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, Timeout, cancellationToken: TestContext.Current.CancellationToken);
return actor;
}
private static (WriteAdmissionTicket Ticket, WriteClaim Claim) NewWrite(string operation, int value,
string driverReference = "plant/tag", string driverInstanceId = "driver")
{
var now = TimeProvider.System.GetTimestamp();
var view = new DataView(new("cluster", "urn:raw", "string", "plant/tag"), DataRealm.Raw, null, 0, "plant/tag");
var admission = new DataWriteAdmission("peer", view, 1, 1, "serving", "driver-incarnation", operation,
now + 60 * TimeProvider.System.TimestampFrequency, "key", DateTimeOffset.UtcNow.AddMinutes(1), "key-version");
var scope = new FrozenWriteScope("cluster", NodeHierarchyKind.Raw, ImmutableArray.Create("plant", "tag"));
var proof = new WriteRouteProof(admission, scope, "RawTag", "tag", null, driverInstanceId, driverReference, 1, 1);
var ticket = new WriteAdmissionTicket(proof, DataValue.FromScalar(DataValueKind.Int32, value), now);
var registry = new WriteOperationRegistry("serving", 8, 8192, TimeSpan.FromMinutes(1));
var claim = registry.Claim("peer", operation, "serving", SHA256.HashData(Encoding.UTF8.GetBytes(operation))).Claim!;
return (ticket, claim);
}
private sealed class RecordingGate : IWriteDispatchGate
{
private int _revoked;
public void Revoke() => Volatile.Write(ref _revoked, 1);
public DataWriteOutcome? TryCommit(WriteAdmissionTicket ticket, WriteClaim claim)
{
if (Volatile.Read(ref _revoked) != 0)
return new(DataWriteState.RejectedBeforeDispatch, 0x801F0000u, "revoked");
if (!claim.TryMarkDispatched())
return new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "claim already terminal");
return null;
}
}
private class LegacyDriver : IDriver, IWritable
{
private int _calls;
private int _shutdowns;
public int Calls => Volatile.Read(ref _calls);
public int Shutdowns => Volatile.Read(ref _shutdowns);
protected void RecordCall() => Interlocked.Increment(ref _calls);
public string DriverInstanceId { get; init; } = "driver";
public string DriverType => "test";
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
public Task ShutdownAsync(CancellationToken cancellationToken) { Interlocked.Increment(ref _shutdowns); return Task.CompletedTask; }
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
public Task<IReadOnlyList<WriteResult>> WriteAsync(IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
RecordCall();
return Task.FromResult<IReadOnlyList<WriteResult>>([new(0)]);
}
}
private sealed class SingleDriverFactory(IDriver driver) : IDriverFactory
{
public IReadOnlyCollection<string> SupportedTypes => ["Modbus"];
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson) => driver;
}
private sealed class BlockingHistorization : IHistorizationRoleView
{
private int _armed;
public bool ShouldRecordHistorizedValues => true;
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ManualResetEventSlim Release { get; } = new();
public void Arm() => Volatile.Write(ref _armed, 1);
public void PublishHistorizationRole(bool shouldRecordHistorizedValues)
{
if (Volatile.Read(ref _armed) == 0) return;
Entered.TrySetResult();
Release.Wait(TimeSpan.FromSeconds(15), CancellationToken.None);
}
}
private sealed class BlockingHistoryUpdate : IHistoryUpdateRoleView
{
private int _armed;
public bool ShouldServeHistoryUpdate => false;
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ManualResetEventSlim Release { get; } = new();
public void Arm() => Volatile.Write(ref _armed, 1);
public void PublishHistoryUpdateRole(bool shouldServeHistoryUpdate)
{
if (Volatile.Read(ref _armed) == 0) return;
Entered.TrySetResult();
Release.Wait(TimeSpan.FromSeconds(15), CancellationToken.None);
}
}
private sealed class PolicyCompletionClock : TimeProvider
{
private readonly ManualTimeProvider _inner = new();
private int _signalNextUtc;
public TaskCompletionSource AfterPolicyUtc { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public void SignalAfterEvaluation() => Volatile.Write(ref _signalNextUtc, 1);
public void Advance(TimeSpan by) => _inner.Advance(by);
public override long TimestampFrequency => _inner.TimestampFrequency;
public override long GetTimestamp() => _inner.GetTimestamp();
public override DateTimeOffset GetUtcNow()
{
var captured = _inner.GetUtcNow();
if (Interlocked.Exchange(ref _signalNextUtc, 0) != 0) AfterPolicyUtc.TrySetResult();
return captured;
}
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) =>
_inner.CreateTimer(callback, state, dueTime, period);
}
private sealed class CompletionSignalingEvaluator(IPermissionEvaluator inner, PolicyCompletionClock clock) : IPermissionEvaluator
{
public AuthorizationDecision Authorize(UserAuthorizationState session, OpcUaOperation operation, NodeScope scope)
{
var result = inner.Authorize(session, operation, scope);
clock.SignalAfterEvaluation();
return result;
}
}
private sealed class RichDriver : LegacyDriver, IWriteOutcomeCapability
{
public bool Hold { get; init; }
public bool HoldFirstOnly { get; init; }
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public async Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes,
CancellationToken cancellationToken)
{
RecordCall();
Entered.TrySetResult();
if (Hold && (!HoldFirstOnly || Calls == 1)) await Release.Task;
return [new(DataWriteState.DriverConfirmedSuccess, 0, null)];
}
}
private sealed class SynchronousThrowDriver : LegacyDriver, IWriteOutcomeCapability
{
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes,
CancellationToken cancellationToken)
{
RecordCall();
throw new InvalidOperationException("driver failed before returning a task");
}
}
private sealed class SynchronousBlockingDriver(ManualResetEventSlim release) : LegacyDriver, IWriteOutcomeCapability
{
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes,
CancellationToken cancellationToken)
{
RecordCall();
Entered.TrySetResult();
release.Wait(TimeSpan.FromSeconds(15), CancellationToken.None);
return Task.FromResult<IReadOnlyList<DataWriteOutcome>>([new(DataWriteState.DriverConfirmedSuccess, 0, null)]);
}
}
private sealed class PausedWriteInvoker : IDriverCapabilityInvoker
{
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public bool SawIdempotent { get; private set; }
public ValueTask<TResult> ExecuteAsync<TResult>(DriverCapability capability, string hostName,
Func<CancellationToken, ValueTask<TResult>> callSite, CancellationToken cancellationToken) => callSite(cancellationToken);
public ValueTask ExecuteAsync(DriverCapability capability, string hostName,
Func<CancellationToken, ValueTask> callSite, CancellationToken cancellationToken) => callSite(cancellationToken);
public async ValueTask<TResult> ExecuteWriteAsync<TResult>(string hostName, bool isIdempotent,
Func<CancellationToken, ValueTask<TResult>> callSite, CancellationToken cancellationToken)
{
SawIdempotent = isIdempotent;
Entered.TrySetResult();
await Release.Task;
return await callSite(cancellationToken);
}
}
}
@@ -0,0 +1,111 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P05")]
[Trait("Category", "Unit")]
public sealed class GrpcDataLateWriteTests
{
private static readonly DataWriteOutcome Unknown = new(DataWriteState.OutcomeUnknown, 0, null);
private static readonly DataWriteOutcome Success = new(DataWriteState.DriverConfirmedSuccess, 0, null);
private static WriteClaim DispatchedClaim()
{
var registry = new WriteOperationRegistry("inc", 2, 4096, TimeSpan.FromMinutes(1));
var claim = registry.Claim("p", "op", "inc", new byte[32]).Claim!;
claim.TryMarkDispatched().ShouldBeTrue();
claim.Complete(Unknown).ShouldBeTrue();
return claim;
}
[Fact]
public async Task Reserved_observer_records_actual_late_result_and_releases_owned_lifetime()
{
var observer = new LateWriteObserver(1, TimeSpan.FromSeconds(10));
var claim = DispatchedClaim();
var source = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
var lifetime = new CountingLifetime();
observer.TryReserve(out var reservation).ShouldBeTrue();
reservation!.Observe(source.Task, claim, lifetime);
observer.TryReserve(out _).ShouldBeFalse();
source.SetResult(Success);
await WaitUntil(() => claim.CurrentOutcome == Success && lifetime.Count == 1);
(await claim.Completion).ShouldBe(Unknown);
observer.TryReserve(out var next).ShouldBeTrue();
next!.Dispose();
}
[Fact]
public async Task Expired_observer_retains_physical_capacity_and_lifetime_until_driver_really_finishes()
{
var clock = new ManualTimeProvider();
var observer = new LateWriteObserver(1, TimeSpan.FromSeconds(10), clock);
var claim = DispatchedClaim();
var source = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
var lifetime = new CountingLifetime();
observer.TryReserve(out var reservation).ShouldBeTrue();
reservation!.Observe(source.Task, claim, lifetime);
clock.Advance(TimeSpan.FromSeconds(11));
observer.TryReserve(out _).ShouldBeFalse();
lifetime.Count.ShouldBe(0);
source.SetResult(Success);
await WaitUntil(() => lifetime.Count == 1);
claim.CurrentOutcome.ShouldBe(Unknown);
observer.TryReserve(out var next).ShouldBeTrue();
next!.Dispose();
}
[Fact]
public async Task Already_completed_driver_is_observed_and_reservation_dispose_is_idempotent()
{
var observer = new LateWriteObserver(1, TimeSpan.FromSeconds(10));
var claim = DispatchedClaim();
var lifetime = new CountingLifetime();
observer.TryReserve(out var reservation).ShouldBeTrue();
reservation!.Observe(Task.FromResult(Success), claim, lifetime);
reservation.Dispose();
await WaitUntil(() => lifetime.Count == 1 && claim.CurrentOutcome == Success);
observer.TryReserve(out var next).ShouldBeTrue();
next!.Dispose();
next.Dispose();
}
[Fact]
public async Task Confirmation_after_unknown_retention_gets_its_own_retry_window()
{
var clock = new ManualTimeProvider();
var registry = new WriteOperationRegistry("inc", 1, 4096, TimeSpan.FromMinutes(1), clock);
var claim = registry.Claim("p", "op", "inc", new byte[32]).Claim!;
claim.TryMarkDispatched().ShouldBeTrue();
claim.Complete(Unknown).ShouldBeTrue();
var observer = new LateWriteObserver(1, TimeSpan.FromMinutes(5), clock);
var source = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
var lifetime = new CountingLifetime();
observer.TryReserve(out var reservation).ShouldBeTrue();
reservation!.Observe(source.Task, claim, lifetime);
clock.Advance(TimeSpan.FromMinutes(2));
source.SetResult(Success);
await WaitUntil(() => lifetime.Count == 1);
var duplicate = registry.Claim("p", "op", "inc", new byte[32]);
duplicate.Kind.ShouldBe(WriteClaimKind.Existing);
duplicate.Claim!.CurrentOutcome.ShouldBe(Success);
(await duplicate.Claim.Completion).ShouldBe(Unknown);
}
private static async Task WaitUntil(Func<bool> condition)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
while (!condition()) await Task.Delay(1, timeout.Token);
}
private sealed class CountingLifetime : IDisposable
{
private int _count;
public int Count => Volatile.Read(ref _count);
public void Dispose() => Interlocked.Increment(ref _count);
}
}
@@ -0,0 +1,389 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P05")]
public sealed class GrpcDataWriteAdmissionTests
{
[Fact]
public async Task Authority_publication_is_ordered_with_dispatch_and_notifications_run_outside_the_fence()
{
var fence = new DataWriteDispatchFence();
var authority = new DataPlaneAuthorityState(fence);
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var notificationCanEnter = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
authority.Changed += snapshot =>
{
// A different thread must acquire the dispatch fence while this callback runs. A reentrant
// acquisition on the notification thread would not detect holding the fence across callbacks.
var enteredFence = new ManualResetEventSlim();
_ = Task.Run(() => { using (fence.Enter()) enteredFence.Set(); }, TestContext.Current.CancellationToken);
notificationCanEnter.TrySetResult(enteredFence.Wait(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken));
};
using var release = new ManualResetEventSlim();
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var owner = Task.Run(() =>
{
using (fence.Enter()) { held.TrySetResult(); release.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
}, TestContext.Current.CancellationToken);
await held.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var apply = Task.Run(() =>
{
entered.TrySetResult();
authority.Apply("cluster", "revision-1", Array.Empty<ApiKey>(), Array.Empty<NodeAcl>(),
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
}, TestContext.Current.CancellationToken);
try
{
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
// Publication, not merely its Changed event, is ordered against the dispatch commit.
(await Task.WhenAny(apply, Task.Delay(150, TestContext.Current.CancellationToken))).ShouldNotBe(apply);
authority.Current.HasArtifact.ShouldBeFalse();
}
finally { release.Set(); }
await owner.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await apply.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
(await notificationCanEnter.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue("Changed must run outside the dispatch fence");
authority.Current.HasArtifact.ShouldBeTrue();
}
[Fact]
public async Task A_catalog_invalidation_cannot_publish_inside_a_dispatch_commit()
{
var fence = new DataWriteDispatchFence();
var catalog = new CatalogActivation(fence);
var epoch = catalog.Begin("first");
catalog.AuthorityInstalled(epoch, 1).ShouldBeTrue();
catalog.Complete(epoch, true).ShouldBeTrue();
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var release = new ManualResetEventSlim();
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var owner = Task.Run(() =>
{
using (fence.Enter()) { held.TrySetResult(); release.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
}, TestContext.Current.CancellationToken);
await held.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var invalidate = Task.Run(() => { started.TrySetResult(); return catalog.Begin("second"); }, TestContext.Current.CancellationToken);
try
{
await started.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
(await Task.WhenAny(invalidate, Task.Delay(150, TestContext.Current.CancellationToken))).ShouldNotBe(invalidate);
catalog.Current.IsReady.ShouldBeTrue();
}
finally { release.Set(); }
await owner.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
(await invalidate.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeGreaterThan(epoch);
catalog.Current.IsReady.ShouldBeFalse();
}
[Fact]
public void Demotion_and_repromotion_advance_the_primary_generation_even_when_the_final_verdict_matches()
{
var role = new RedundancyRoleView(new DataWriteDispatchFence());
role.PublishPrimaryRole(true);
var before = role.PrimaryGeneration;
role.PublishPrimaryRole(false);
var demoted = role.PrimaryGeneration;
role.PublishPrimaryRole(true);
demoted.ShouldBeGreaterThan(before);
role.PrimaryGeneration.ShouldBeGreaterThan(demoted);
role.ShouldActAsPrimary.ShouldBeTrue();
}
[Fact]
public void First_primary_publication_establishes_a_generation_without_heartbeat_churn()
{
var role = new RedundancyRoleView(new DataWriteDispatchFence());
role.ShouldActAsPrimary.ShouldBeTrue(); // the legacy seed is preserved
role.PrimaryGeneration.ShouldBe(0);
role.PublishPrimaryRole(true);
var established = role.PrimaryGeneration;
established.ShouldBeGreaterThan(0);
role.PublishPrimaryRole(true);
role.PrimaryGeneration.ShouldBe(established);
}
[Fact]
public void Route_proof_is_invalidated_by_remap_and_does_not_revive_when_the_original_route_returns()
{
var state = new WriteRouteState(new DataWriteDispatchFence());
var view = new DataView(new("cluster", "urn:raw", "string", "plant/tag"), DataRealm.Raw, null, 0, "plant/tag");
var original = state.Publish(view, "driver", "plant/tag", "incarnation-1");
state.IsCurrent(view, original).ShouldBeTrue();
state.Publish(view, "other-driver", "plant/other", "incarnation-2");
state.IsCurrent(view, original).ShouldBeFalse();
var restored = state.Publish(view, "driver", "plant/tag", "incarnation-1");
state.IsCurrent(view, original).ShouldBeFalse();
state.IsCurrent(view, restored).ShouldBeTrue();
restored.RouteGeneration.ShouldBeGreaterThan(original.RouteGeneration);
}
[Fact]
public async Task Executor_keeps_partial_batch_results_in_input_order_and_does_not_dispatch_a_type_mismatch()
{
using var fixture = new LocalDataFixture();
var route = new RecordingRoute(fixture.Raw);
var executor = CreateExecutor(fixture, route);
using var first = DataValue.FromScalar(DataValueKind.Int32, 1);
using var wrong = DataValue.FromScalar(DataValueKind.String, "wrong type");
using var last = DataValue.FromScalar(DataValueKind.Int32, 2);
var remaining = TimeSpan.FromSeconds(5);
var results = await executor.WriteAsync(new([
new("a", "ok", fixture.Raw, first, 1, fixture.Serving.Incarnation, remaining),
new("b", "bad-type", fixture.Raw, wrong, 1, fixture.Serving.Incarnation, remaining),
new("c", "failed", fixture.Raw, last, 1, fixture.Serving.Incarnation, remaining)],
LocalDataFixture.Budget), TestContext.Current.CancellationToken);
results.Select(x => x.CorrelationId).ShouldBe(["a", "b", "c"]);
results.Select(x => x.Outcome.State).ShouldBe([DataWriteState.DriverConfirmedSuccess,
DataWriteState.RejectedBeforeDispatch, DataWriteState.DriverConfirmedFailure]);
route.Dispatched.Order().ShouldBe(["failed", "ok"]);
}
[Fact]
public async Task Executor_joins_concurrent_duplicate_with_a_different_remaining_budget()
{
using var fixture = new LocalDataFixture();
var route = new RecordingRoute(fixture.Raw) { Hold = true };
var executor = CreateExecutor(fixture, route);
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 42);
using var duplicateValue = DataValue.FromScalar(DataValueKind.Int32, 42);
var first = executor.WriteAsync(new([new("first", "same-operation", fixture.Raw, firstValue, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await route.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var duplicate = executor.WriteAsync(new([new("duplicate", "same-operation", fixture.Raw, duplicateValue, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(4))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
route.Release.TrySetResult();
var firstResult = await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var duplicateResult = await duplicate.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
firstResult.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
duplicateResult.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
route.Dispatched.ShouldBe(["same-operation"]);
}
[Fact]
public async Task Equivalent_origin_cluster_spelling_uses_the_catalog_resolved_view_for_duplicate_identity()
{
using var fixture = new LocalDataFixture();
var route = new RecordingRoute(fixture.Raw) { Hold = true };
var executor = CreateExecutor(fixture, route);
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 42);
using var secondValue = DataValue.FromScalar(DataValueKind.Int32, 42);
var first = executor.WriteAsync(new([new("first", "canonical-view", fixture.Raw, firstValue, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await route.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var equivalent = fixture.Raw with { Address = fixture.Raw.Address with { OriginClusterId = "CLUSTER" } };
var second = executor.WriteAsync(new([new("second", "canonical-view", equivalent, secondValue, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
route.Release.TrySetResult();
(await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken))
.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
(await second.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken))
.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
route.Dispatched.ShouldBe(["canonical-view"]);
}
[Fact]
public async Task Ordinally_distinct_authorized_views_with_unpaired_surrogates_cannot_share_an_operation()
{
using var fixture = new LocalDataFixture();
var existing = fixture.Catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
var first = fixture.Raw with { Address = fixture.Raw.Address with { Identifier = "Plant/Driver/Device/\ud800" },
Subject = "Plant/Driver/Device/\ud800" };
var second = fixture.Raw with { Address = fixture.Raw.Address with { Identifier = "Plant/Driver/Device/\ud801" },
Subject = "Plant/Driver/Device/\ud801" };
LocalDataNode MakeNode(string id, DataView view, string leaf) => existing with
{
EntityId = id,
Metadata = existing.Metadata with { View = view, BrowseName = leaf },
Scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw,
Segments = ["Plant", "Driver", "Device", leaf] },
};
var nodes = fixture.Catalog.Nodes.Concat([MakeNode("surrogate-a", first, "\ud800"), MakeNode("surrogate-b", second, "\ud801")]);
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
var catalog = new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(), nodes,
[new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw,
RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations }]);
var route = new RecordingRoute(first, second);
var executor = CreateExecutor(fixture, route, catalog: catalog);
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 42);
using var secondValue = DataValue.FromScalar(DataValueKind.Int32, 42);
var one = await executor.WriteAsync(new([new("one", "same-id", first, firstValue, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
var two = await executor.WriteAsync(new([new("two", "same-id", second, secondValue, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
one.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
two.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
route.Dispatched.ShouldBe(["same-id"]);
}
[Fact]
public async Task Canceling_one_waiter_does_not_cancel_the_shared_dispatched_write()
{
using var fixture = new LocalDataFixture();
var route = new RecordingRoute(fixture.Raw) { Hold = true };
var executor = CreateExecutor(fixture, route);
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
using var canceledWaiter = new CancellationTokenSource();
var batch = new WriteBatch([new("first", "shared", fixture.Raw, value, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget);
var first = executor.WriteAsync(batch, canceledWaiter.Token);
await route.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var second = executor.WriteAsync(batch, TestContext.Current.CancellationToken);
canceledWaiter.Cancel();
route.Release.TrySetResult();
try { await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
catch (OperationCanceledException) { }
(await second.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldHaveSingleItem().Outcome.State
.ShouldBe(DataWriteState.DriverConfirmedSuccess);
route.Dispatched.ShouldBe(["shared"]);
}
[Fact]
public async Task Executor_does_not_refine_an_unknown_after_the_observation_window_ends()
{
using var fixture = new LocalDataFixture();
var route = new ExpiredObservationRoute(fixture.Raw, fixture.Clock);
var executor = CreateExecutor(fixture, route);
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
var batch = new WriteBatch([new("first", "late-result", fixture.Raw, value, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget);
var first = await executor.WriteAsync(batch, TestContext.Current.CancellationToken);
var duplicate = await executor.WriteAsync(batch, TestContext.Current.CancellationToken);
first.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
duplicate.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
route.Dispatches.ShouldBe(1);
}
[Theory]
[InlineData("expired")]
[InlineData("principal")]
[InlineData("version")]
[InlineData("budget")]
public async Task Executor_rejects_unusable_original_credentials_and_insufficient_budget_before_any_route_call(string reason)
{
using var fixture = new LocalDataFixture();
var route = new RecordingRoute(fixture.Raw);
var context = reason switch
{
"expired" => fixture.Context with { CredentialExpiresUtc = fixture.Clock.GetUtcNow() },
"principal" => fixture.Context with { PrincipalId = "different-principal" },
"version" => fixture.Context with { CredentialVersion = "replaced-key-version" },
_ => fixture.Context,
};
var executor = CreateExecutor(fixture, route, context);
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
var remaining = reason == "budget" ? TimeSpan.FromMilliseconds(1) : TimeSpan.FromSeconds(5);
var result = await executor.WriteAsync(new([new("one", "operation", fixture.Raw, value, 1,
fixture.Serving.Incarnation, remaining)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
route.Dispatched.ShouldBeEmpty();
}
private static DataWriteExecutor CreateExecutor(LocalDataFixture fixture, IDataWriteRoute route,
DataAuthenticatedContext? context = null, LocalExportCatalog? catalog = null)
{
var authority = new DataPlaneAuthorityState();
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
authority.Apply("cluster", "first", [key],
[new NodeAcl { NodeAclId = "write", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder,
ScopeId = "folder", PermissionFlags = NodePermissions.WriteOperate }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, fixture.Clock), fixture.Clock);
var registry = new WriteOperationRegistry(fixture.Serving.Incarnation, 16, 16_384, TimeSpan.FromMinutes(1), fixture.Clock);
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilitiesProvider("cluster", () => fixture.Serving, () => true, limits);
return new DataWriteExecutor(context ?? fixture.Context, () => catalog ?? fixture.Catalog, policy, capabilities, route,
registry, new WriteValueBudget(16_384), fixture.Clock, new DriverWriteBounds(TimeSpan.FromMilliseconds(100)));
}
private sealed class RecordingRoute(DataView view, DataView? alternate = null) : IDataWriteRoute
{
private readonly System.Collections.Concurrent.ConcurrentQueue<string> _dispatched = new();
private readonly LateWriteObserver _observer = new(16, TimeSpan.FromMinutes(1));
public bool Hold { get; init; }
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public string[] Dispatched => _dispatched.ToArray();
public bool TryResolve(DataView requested, out WriteRouteTarget? target)
{
target = requested == view || requested == alternate
? new("driver", "Plant/Driver/Device/Speed", "driver-incarnation", 1, 1) : null;
return target is not null;
}
public async Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct)
{
var operation = ticket.Proof.Admission.OperationId;
_observer.TryReserve(out var reservation).ShouldBeTrue();
var physical = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
reservation.ShouldNotBeNull().Observe(physical.Task, claim, ticket);
_dispatched.Enqueue(operation);
claim.TryMarkDispatched().ShouldBeTrue();
Entered.TrySetResult();
if (Hold) await Release.Task;
var outcome = operation == "failed"
? new DataWriteOutcome(DataWriteState.DriverConfirmedFailure, 0x80000000u, "device rejected")
: new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null);
physical.TrySetResult(outcome);
return outcome;
}
}
private sealed class ExpiredObservationRoute(DataView view, ManualTimeProvider clock) : IDataWriteRoute
{
public int Dispatches { get; private set; }
public bool TryResolve(DataView requested, out WriteRouteTarget? target)
{
target = requested == view ? new("driver", "Plant/Driver/Device/Speed", "driver-incarnation", 1, 1) : null;
return target is not null;
}
public Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct)
{
Dispatches++;
claim.TryMarkDispatched().ShouldBeTrue();
var observer = new LateWriteObserver(1, TimeSpan.FromMilliseconds(100), new StepPastRetentionClock(clock));
observer.TryReserve(out var reservation).ShouldBeTrue();
var confirmed = new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null);
// The completed physical task lets Observe settle the expired result synchronously, before the
// host route returns the same definitive outcome to the executor.
reservation.ShouldNotBeNull().Observe(Task.FromResult(confirmed), claim, ticket);
return Task.FromResult(confirmed);
}
}
private sealed class StepPastRetentionClock(ManualTimeProvider clock) : TimeProvider
{
private int _reads;
public override long TimestampFrequency => clock.TimestampFrequency;
public override DateTimeOffset GetUtcNow() => clock.GetUtcNow();
public override long GetTimestamp()
{
if (Interlocked.Increment(ref _reads) == 2) clock.Advance(TimeSpan.FromSeconds(1));
return clock.GetTimestamp();
}
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) =>
clock.CreateTimer(callback, state, dueTime, period);
}
}
@@ -0,0 +1,47 @@
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P05")]
public sealed class GrpcDataWriteCompositionTests
{
[Fact]
public void Runtime_registration_shares_the_publication_fence_with_authority_and_primary_state()
{
var services = new ServiceCollection();
// Host registers authority before adding the runtime services. Construction must still
// receive the same fence as the role publisher and the later catalog activation.
services.AddSingleton<DataPlaneAuthorityState>();
services.AddSingleton<CatalogActivation>();
services.AddOtOpcUaRuntime();
using var provider = services.BuildServiceProvider();
var fence = provider.GetRequiredService<DataWriteDispatchFence>();
ReferenceEquals(fence, provider.GetRequiredService<DataPlaneAuthorityState>().DispatchFence).ShouldBeTrue();
ReferenceEquals(fence, provider.GetRequiredService<RedundancyRoleView>().DispatchFence).ShouldBeTrue();
ReferenceEquals(fence, provider.GetRequiredService<CatalogActivation>().DispatchFence).ShouldBeTrue();
}
[Fact]
public void Runtime_registration_preserves_an_explicit_fence_and_is_idempotent()
{
var services = new ServiceCollection();
var fence = new DataWriteDispatchFence();
services.AddSingleton(fence);
services.AddSingleton<DataPlaneAuthorityState>();
services.AddOtOpcUaRuntime();
services.AddOtOpcUaRuntime();
using var provider = services.BuildServiceProvider();
var registered = provider.GetServices<DataWriteDispatchFence>().ToArray();
registered.Length.ShouldBe(1);
ReferenceEquals(registered[0], fence).ShouldBeTrue();
ReferenceEquals(fence, provider.GetRequiredService<DataPlaneAuthorityState>().DispatchFence).ShouldBeTrue();
ReferenceEquals(fence, provider.GetRequiredService<RedundancyRoleView>().DispatchFence).ShouldBeTrue();
}
}
@@ -0,0 +1,96 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P05")]
[Trait("Category", "Unit")]
public sealed class GrpcDataWriteRegistryTests
{
private static readonly byte[] Hash = new byte[32];
private static readonly DataWriteOutcome Success = new(DataWriteState.DriverConfirmedSuccess, 0, null);
private static WriteOperationRegistry Registry(int count = 4, long bytes = 4096, ManualTimeProvider? clock = null) =>
new("inc-1", count, bytes, TimeSpan.FromSeconds(10), clock);
[Fact]
public async Task Concurrent_duplicates_share_one_claim_and_waiter_cancellation_does_not_cancel_work()
{
var registry = Registry();
var results = await Task.WhenAll(Enumerable.Range(0, 32).Select(_ => Task.Run(() =>
registry.Claim("principal", "op", "inc-1", Hash))));
results.Count(r => r.Kind == WriteClaimKind.Owner).ShouldBe(1);
var owner = results.Single(r => r.Kind == WriteClaimKind.Owner).Claim!;
results.ShouldAllBe(r => ReferenceEquals(r.Claim, owner));
owner.TryMarkDispatched().ShouldBeTrue();
using var cancellation = new CancellationTokenSource();
var detached = owner.Completion.WaitAsync(cancellation.Token);
cancellation.Cancel();
await Should.ThrowAsync<OperationCanceledException>(async () => await detached);
owner.Complete(Success).ShouldBeTrue();
(await owner.Completion).ShouldBe(Success);
registry.Claim("principal", "op", "inc-1", Hash).Claim!.CurrentOutcome.ShouldBe(Success);
}
[Fact]
public void Hash_is_copied_and_conflicting_payload_or_stale_incarnation_cannot_dispatch()
{
var registry = Registry();
var semantic = new byte[32];
var owner = registry.Claim("principal", "op", "inc-1", semantic);
semantic[0] = 1;
registry.Claim("principal", "op", "inc-1", semantic).Kind.ShouldBe(WriteClaimKind.Conflict);
registry.Claim("principal", "op", "old-inc", Hash).Kind.ShouldBe(WriteClaimKind.Stale);
registry.Claim("principal", "op", "inc-1", Hash).Claim.ShouldBeSameAs(owner.Claim);
registry.Claim("other-principal", "op", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Owner);
Should.Throw<ArgumentException>(() => registry.Claim("principal", "bad", "inc-1", new byte[31]));
}
[Fact]
public void Principal_identity_is_case_insensitive_but_operation_id_is_ordinal()
{
var registry = Registry();
var first = registry.Claim("Service-Principal", "Operation", "inc-1", Hash);
registry.Claim("service-principal", "Operation", "inc-1", Hash).Claim.ShouldBeSameAs(first.Claim);
registry.Claim("service-principal", "operation", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Owner);
}
[Fact]
public void Inflight_entries_are_never_evicted_and_completed_retention_uses_monotonic_time()
{
var clock = new ManualTimeProvider();
var registry = Registry(count: 1, clock: clock);
var claim = registry.Claim("p", "one", "inc-1", Hash).Claim!;
clock.Advance(TimeSpan.FromMinutes(1));
registry.Claim("p", "two", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Capacity);
registry.Claim("p", "one", "inc-1", Hash).Claim.ShouldBeSameAs(claim);
claim.Complete(new(DataWriteState.RejectedBeforeDispatch, 0, null)).ShouldBeTrue();
clock.WallClockOffset = TimeSpan.FromDays(30);
registry.Claim("p", "two", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Capacity);
clock.Advance(TimeSpan.FromSeconds(11));
registry.Claim("p", "two", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Owner);
}
[Fact]
public void Retained_byte_capacity_rejects_without_evicting_existing_claim()
{
var registry = Registry(bytes: 1);
registry.Claim("principal", "op", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Capacity);
}
[Fact]
public async Task Late_refinement_updates_snapshot_without_changing_already_completed_unknown_task()
{
var claim = Registry().Claim("p", "one", "inc-1", Hash).Claim!;
claim.TryMarkDispatched().ShouldBeTrue();
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0, null);
claim.Complete(unknown).ShouldBeTrue();
claim.LateRefine(Success).ShouldBeTrue();
(await claim.Completion).ShouldBe(unknown);
claim.CurrentOutcome.ShouldBe(Success);
claim.LateRefine(new(DataWriteState.RejectedBeforeDispatch, 0, null)).ShouldBeFalse();
}
}