Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDeployBookkeepingTests.cs
T
Joseph Doherty a0f41a30d8 fix(deploy): #977 deploy/apply bookkeeping — planner sees every composition field, degraded/restarted applies repair, failed deploys restore the last applied revision, superseded deployments close
- U-2: planner diffs the rich scripted-alarm plans; an Enabled flip is a surgical add/remove of the one
  condition, a Name/AlarmType/Severity edit on an enabled alarm rebuilds.
- U-3: planner diffs UNS Areas/Lines in full; a Line moved to another Area rebuilds, added/removed
  Areas/Lines are surgical.
- U-9: removing the last VirtualTag in a FolderPath removes the sub-folder in place.
- AddressSpacePlannerFieldCoverageTests reflects over every composition list + record field.
- R-4: while the last applied composition is degraded, a non-rebuild apply re-ensures the full composition.
- R-20: a supervision restart of OpcUaPublishActor forces its first apply to rebuild.
- R-1: Direct boot with a Failed/orphan newest row restores the newest Applied deployment, then the cache.
- R-15: the revision advances after the last throwing apply step; a throw marks it unconfirmed.
- H-4: ConfigPublishCoordinator closes a superseded in-flight deployment (TimedOut + reason).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 10:46:47 -05:00

151 lines
7.9 KiB
C#

using Akka.Actor;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
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.DeploymentCache;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Gitea #977 — deploy bookkeeping on the driver host: R-1 (a restart after a FAILED deploy must serve the last
/// APPLIED deployment, not boot empty) and R-15 (an apply that throws part-way must not leave its revision looking
/// cleanly served, so a re-dispatch re-applies).
/// </summary>
public sealed class DriverHostActorDeployBookkeepingTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("driver-test");
private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64));
private static readonly RevisionHash RevB = RevisionHash.Parse(new string('b', 64));
[Fact]
public void A_restart_after_a_failed_deploy_restores_the_last_applied_deployment()
{
var db = NewInMemoryDbFactory();
var a = Seed(db, RevA, "speed");
var b = Seed(db, RevB, "pressure");
var t0 = DateTime.UtcNow.AddMinutes(-10);
AddNodeRow(db, a, NodeDeploymentStatus.Applied, t0);
AddNodeRow(db, b, NodeDeploymentStatus.Failed, t0.AddMinutes(5), "apply threw"); // NEWER, failed
var publish = CreateTestProbe();
var coordinator = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref, localRoles: new HashSet<string> { "driver" }, opcUaPublishActor: publish.Ref));
// The address space is rebuilt from A's artifact — before the fix the Failed arm went straight to an empty Steady.
var rebuild = publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(
m => m.DeploymentId == a, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
rebuild.Artifact.ShouldBe(ArtifactOf(db, a));
// And A is the CURRENT revision: a re-dispatch of A is the idempotent clean ack, not a re-apply.
host.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId()));
coordinator.FishForMessage<ApplyAck>(m => m.DeploymentId == a, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
}
[Fact]
public void A_newest_applied_row_is_restored_exactly_as_before()
{
// Positive control for the selection above: the ordinary Applied-newest boot is unchanged.
var db = NewInMemoryDbFactory();
var a = Seed(db, RevA, "speed");
AddNodeRow(db, a, NodeDeploymentStatus.Applied, DateTime.UtcNow);
var publish = CreateTestProbe();
Sys.ActorOf(DriverHostActor.Props(
db, TestNode, CreateTestProbe().Ref, localRoles: new HashSet<string> { "driver" }, opcUaPublishActor: publish.Ref));
publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(
m => m.DeploymentId == a, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public void A_failed_only_history_falls_back_to_the_node_local_cache()
{
var db = NewInMemoryDbFactory();
var b = Seed(db, RevB, "pressure");
AddNodeRow(db, b, NodeDeploymentStatus.Failed, DateTime.UtcNow, "apply threw");
var cachedBytes = ArtifactOf(db, b);
var cachedId = DeploymentId.NewId();
var cache = new FixedCache(new CachedDeploymentArtifact(
cachedId.ToString(), RevA.Value, cachedBytes, DateTimeOffset.UtcNow));
var publish = CreateTestProbe();
Sys.ActorOf(DriverHostActor.Props(
db, TestNode, CreateTestProbe().Ref, localRoles: new HashSet<string> { "driver" }, opcUaPublishActor: publish.Ref,
deploymentArtifactCache: cache));
publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(
m => m.DeploymentId == cachedId, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public void An_apply_that_throws_after_reconcile_leaves_its_revision_unconfirmed_so_a_redispatch_reapplies()
{
var db = NewInMemoryDbFactory();
var a = Seed(db, RevA, "speed");
var throwOnce = 1;
var catalog = new LocalCatalogCoordinator(new CatalogActivation(), new DataPlaneAuthorityState(),
() => new ServingIdentity(TestNode.Value, "process-1", "Primary", 0, 0));
catalog.BeforeSubscriptionApplyForTests = () =>
{
if (Interlocked.Exchange(ref throwOnce, 0) == 1) throw new InvalidOperationException("subscription work failed");
};
var publish = CreateTestProbe();
var coordinator = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref, localRoles: new HashSet<string> { "driver" }, opcUaPublishActor: publish.Ref,
catalogCoordinator: catalog));
host.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId()));
coordinator.FishForMessage<ApplyAck>(m => m.DeploymentId == a, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Failed);
// Same revision again: it was never served, so it must RE-APPLY (an outcome-reporting rebuild), not short-circuit
// to an immediate clean Applied.
host.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId()));
publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(
m => m.DeploymentId == a && m.ReportOutcome, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
private static DeploymentId Seed(IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev, string tag) =>
V3ArtifactSeeder.SeedV3Deployment(db, rev,
rawTags: new[] { (Driver: "drv-1", DriverName: "Modbus", Device: "dev1", Tag: tag, DataType: "Double", Writable: false) },
unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: tag, Effective: (string?)null) });
private static void AddNodeRow(IDbContextFactory<OtOpcUaConfigDbContext> db, DeploymentId id, NodeDeploymentStatus status,
DateTime startedAtUtc, string? reason = null)
{
using var ctx = db.CreateDbContext();
ctx.NodeDeploymentStates.Add(new NodeDeploymentState
{
NodeId = TestNode.Value, DeploymentId = id.Value, Status = status, StartedAtUtc = startedAtUtc,
AppliedAtUtc = status == NodeDeploymentStatus.Applied ? startedAtUtc : null, FailureReason = reason,
});
ctx.SaveChanges();
}
private static byte[] ArtifactOf(IDbContextFactory<OtOpcUaConfigDbContext> db, DeploymentId id)
{
using var ctx = db.CreateDbContext();
return ctx.Deployments.Single(d => d.DeploymentId == id.Value).ArtifactBlob!;
}
private sealed class FixedCache(CachedDeploymentArtifact artifact) : IDeploymentArtifactCache
{
public Task StoreAsync(string clusterId, string deploymentId, string revisionHash, byte[] bytes, CancellationToken ct = default) => Task.CompletedTask;
public Task<CachedDeploymentArtifact?> GetCurrentAsync(string clusterId, CancellationToken ct = default) => Task.FromResult<CachedDeploymentArtifact?>(artifact);
public Task<CachedDeploymentArtifact?> GetCurrentUnkeyedAsync(CancellationToken ct = default) => Task.FromResult<CachedDeploymentArtifact?>(artifact);
}
}