Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs
T
Joseph Doherty bcd4a9aa29 fix(grpc-data): #964 rich write releases its late-write slot before replying / freeing the tag
The late-write observer released the physical slot on its own continuation of
the driver task, while RunRichWriteAsync replied and told WriteCompleted on
another. A next write to the same target (queued, or sent right after the
reply) could reach TryReserve before the release and be rejected with
'Outstanding driver write capacity exhausted' although nothing was
outstanding. LateWriteReservation.Observe now returns a task that completes
after the slot is released; the actor awaits it (when the physical write has
finished) before replying and freeing the tag. The flaky unit test waited on
the lifetime counter, which is disposed just before the release - it now
awaits the settled task.

Repro: 200 sequential same-target actor writes failed 3/3 runs (no load);
0 failures in 15 runs at load avg ~468. Unit signal: lifetime-wait 22-39 /
2M false 'slot busy', settled-wait 0/2M.
2026-12-02 13:10:20 -05:00

705 lines
42 KiB
C#

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")]
[InlineData("warm-standby-fence")]
[InlineData("warm-return-active-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, catalog.Serving);
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":
case "warm-standby-fence":
case "warm-return-active-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);
if (change == "current-key-expiry-fence") clock.Advance(TimeSpan.FromSeconds(2));
else
{
serving = serving with { Role = change == "warm-standby-fence" ? "Standby" : "Primary", ServingGeneration = 2 };
role.PrimaryGeneration.ShouldBe(proof.PrimaryGeneration, "the driver's Primary verdict has not changed");
}
}
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 Sequential_writes_to_one_target_never_see_the_previous_writes_physical_slot()
{
// #964: the reply and WriteCompleted used to race the late-write observer's slot release, so a
// caller that wrote the same tag again right after its previous reply could be rejected with
// "Outstanding driver write capacity exhausted" although nothing was outstanding any more.
var driver = new RichDriver();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)), maxWrites: 1);
for (var i = 0; i < 200; i++)
{
var (ticket, claim) = NewWrite($"seq-{i}", i);
var outcome = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess, $"write {i}: {outcome.Diagnostic}");
}
driver.Calls.ShouldBe(200);
}
[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);
}
}
}