fix(deploy): #949 ask timeout on the deploy trigger is OutcomeUnknown (202 + pre-allocated id), not a failure; slow-compose phase timings

The id is allocated before the ask and travels in StartDeployment, so a timed-out
caller can name and poll the deployment that may still go ahead. REST answers 202
OutcomeUnknown with a Location; the AdminUI shows 'could not be confirmed, may still
be created'; a retry during a running compose gets 409 naming the same id. The actor
logs per-phase timings for composes slower than 3 s.
This commit is contained in:
Joseph Doherty
2026-12-01 19:27:13 -05:00
parent 6b60845931
commit 88c9766ab5
14 changed files with 333 additions and 15 deletions
@@ -0,0 +1,102 @@
using Akka.Hosting;
using Akka.TestKit.Xunit;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Clients;
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Acls;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.ControlPlane;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests;
/// <summary>
/// lmxopcua#949 — an ask timeout on the deploy trigger is not a failure: the slow compose goes on to create
/// the row after the client gave up. The client must report <c>OutcomeUnknown</c> carrying the id it
/// pre-allocated, and that id must be the one the late deployment ends up with.
/// </summary>
public sealed class AdminOperationsClientDeployTimeoutTests : TestKit
{
// The deploy handler reads Cluster.Get(system).SelfAddress (the audit SourceNode), so the system needs the
// cluster provider; without it the actor throws on the first StartDeployment and the message is lost.
private const string ClusterHocon = """
akka {
loglevel = "WARNING"
actor.provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"
remote.dot-netty.tcp { hostname = "127.0.0.1", port = 0 }
cluster { seed-nodes = [], roles = ["admin"], min-nr-of-members = 1, run-coordinated-shutdown-when-down = off }
}
""";
public AdminOperationsClientDeployTimeoutTests() : base(ClusterHocon)
{
var cluster = Akka.Cluster.Cluster.Get(Sys);
cluster.Join(cluster.SelfAddress);
}
/// <summary>A compose slower than the ask timeout yields OutcomeUnknown + the id the row later carries.</summary>
[Fact]
public async Task Ask_timeout_reports_OutcomeUnknown_with_the_id_the_late_deployment_carries()
{
var gated = new GatedFactory(AclScopeTestDb.Factory($"deploy-timeout-{Guid.NewGuid():N}"));
var coordinator = CreateTestProbe("coordinator");
var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
var registry = new ActorRegistry();
registry.Register<AdminOperationsActorKey>(actor);
var client = new AdminOperationsClient(registry, TimeSpan.FromMilliseconds(500));
gated.Hold();
var result = await client.StartDeploymentAsync("ci", CancellationToken.None);
result.Outcome.ShouldBe(StartDeploymentOutcome.OutcomeUnknown);
result.DeploymentId.ShouldNotBeNull();
result.Message.ShouldNotBeNull().ShouldContain(result.DeploymentId!.Value.Value.ToString());
// The compose was only slow: once it finishes, the deployment exists under exactly that id.
gated.Release();
var dispatch = coordinator.ExpectMsg<ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.DispatchDeployment>(
TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken);
dispatch.DeploymentId.ShouldBe(result.DeploymentId!.Value);
await using var db = await gated.CreateDbContextAsync(TestContext.Current.CancellationToken);
(await db.Deployments.AsNoTracking().SingleAsync(TestContext.Current.CancellationToken))
.DeploymentId.ShouldBe(result.DeploymentId.Value.Value);
}
/// <summary>A caller-initiated cancellation is still a cancellation, not an unknown outcome.</summary>
[Fact]
public async Task Caller_cancellation_still_throws()
{
var gated = new GatedFactory(AclScopeTestDb.Factory($"deploy-cancel-{Guid.NewGuid():N}"));
var actor = Sys.ActorOf(AdminOperationsActor.Props(
gated, CreateTestProbe("coordinator").Ref, Enumerable.Empty<IDriverProbe>()));
var registry = new ActorRegistry();
registry.Register<AdminOperationsActorKey>(actor);
var client = new AdminOperationsClient(registry, TimeSpan.FromSeconds(30));
using var cts = new CancellationTokenSource();
gated.Hold();
var pending = client.StartDeploymentAsync("ci", cts.Token);
await cts.CancelAsync();
await Should.ThrowAsync<OperationCanceledException>(() => pending);
gated.Release();
}
private sealed class GatedFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
private volatile TaskCompletionSource? _gate;
public void Hold() => _gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
public void Release() => _gate?.TrySetResult();
public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext();
public async Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default)
{
if (_gate is { } gate) await gate.Task.WaitAsync(cancellationToken);
return inner.CreateDbContext();
}
}
}
@@ -46,6 +46,7 @@ public sealed class DeployApiEndpointsTests
[InlineData(StartDeploymentOutcome.NoChanges, StatusCodes.Status200OK)]
[InlineData(StartDeploymentOutcome.AnotherDeploymentInFlight, StatusCodes.Status409Conflict)]
[InlineData(StartDeploymentOutcome.Rejected, StatusCodes.Status422UnprocessableEntity)]
[InlineData(StartDeploymentOutcome.OutcomeUnknown, StatusCodes.Status202Accepted)]
public void ToResult_maps_outcome_to_status(StartDeploymentOutcome outcome, int expectedStatus)
{
var result = DeployApiEndpoints.ToResult(
@@ -55,4 +56,35 @@ public sealed class DeployApiEndpointsTests
result.ShouldBeAssignableTo<IStatusCodeHttpResult>();
((IStatusCodeHttpResult)result).StatusCode.ShouldBe(expectedStatus);
}
/// <summary>
/// lmxopcua#949: an ask timeout is not a failure. The REST trigger answers 202 with the pre-allocated id in
/// the body and the Location, so the caller can poll for the deployment that may still go ahead.
/// </summary>
[Fact]
public void ToResult_OutcomeUnknown_is_202_with_the_preallocated_id_and_a_pollable_Location()
{
var id = Guid.NewGuid();
var result = DeployApiEndpoints.ToResult(new StartDeploymentResult(
StartDeploymentOutcome.OutcomeUnknown, new DeploymentId(id), RevisionHash: null,
Message: "no reply", CorrelationId: CorrelationId.NewId()));
var accepted = result.ShouldBeOfType<Microsoft.AspNetCore.Http.HttpResults.Accepted<DeployApiEndpoints.DeployResponse>>();
accepted.Location.ShouldBe($"/api/deployments/{id}");
accepted.Value!.Outcome.ShouldBe("OutcomeUnknown");
accepted.Value.DeploymentId.ShouldBe(id);
accepted.Value.Message.ShouldBe("no reply");
}
/// <summary>A 409 for a compose still running names the deployment that is going ahead (#949).</summary>
[Fact]
public void ToResult_InFlight_carries_the_in_flight_id()
{
var id = Guid.NewGuid();
var result = DeployApiEndpoints.ToResult(new StartDeploymentResult(
StartDeploymentOutcome.AnotherDeploymentInFlight, new DeploymentId(id), null, "busy", CorrelationId.NewId()));
var conflict = result.ShouldBeOfType<Microsoft.AspNetCore.Http.HttpResults.Conflict<DeployApiEndpoints.DeployResponse>>();
conflict.Value!.DeploymentId.ShouldBe(id);
}
}
@@ -117,6 +117,19 @@ public sealed class DeploymentRefreshTests : BunitContext
cut.Find("[role=status]").TextContent.ShouldNotContain("Request rejected");
}
/// <summary>lmxopcua#949: an ask timeout is shown as "may still be created", never as a failure or rejection, and names the id.</summary>
[Fact]
public void OutcomeUnknown_IsShownAsUnconfirmed_WithTheRequestedId()
{
Configure();var cut=Render<DeploymentPage>();var id=Guid.NewGuid();
Request.Start=()=>Task.FromResult(new StartDeploymentResult(StartDeploymentOutcome.OutcomeUnknown,new(id),null,"no reply",new(Guid.NewGuid())));
cut.Find("[data-testid=deployment-request]").Click();
cut.WaitForAssertion(()=>cut.Find("[role=status]").TextContent.ShouldContain("could not be confirmed"));
var text=cut.Find("[role=status]").TextContent;
text.ShouldContain("may still be created");text.ShouldNotContain("rejected");text.ShouldNotContain("No deployment history");
cut.Markup.ShouldContain(id.ToString());
}
[Fact]
public async Task DelayedInitialHistory_ComposesDriftOnceAfterRowsBecomeAvailable()
{
@@ -116,6 +116,34 @@ public sealed class AdminOperationsActorMailboxTests : ControlPlaneActorTestBase
coordinator.ExpectMsg<DispatchDeployment>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>
/// lmxopcua#949: the refusal for a second request names the deployment that is being composed — a caller
/// whose first ask timed out and who retries learns the id of the deployment going ahead.
/// </summary>
[Fact]
public void Refusal_during_an_in_flight_compose_names_the_deployment_being_composed()
{
var gated = new GatedDbFactory(NewInMemoryDbFactory());
var coordinator = CreateTestProbe("coord");
var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
var first = CreateTestProbe("first");
var second = CreateTestProbe("second");
var firstId = DeploymentId.NewId();
gated.Hold();
first.Send(actor, new StartDeployment("joe", CorrelationId.NewId(), firstId));
gated.Entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
second.Send(actor, new StartDeployment("kim", CorrelationId.NewId(), DeploymentId.NewId()));
var refusal = second.ExpectMsg<StartDeploymentResult>(AckBudget, cancellationToken: TestContext.Current.CancellationToken);
refusal.Outcome.ShouldBe(StartDeploymentOutcome.AnotherDeploymentInFlight);
refusal.DeploymentId.ShouldBe(firstId);
gated.Release();
first.ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
.DeploymentId.ShouldBe(firstId);
}
private sealed class BlockingProbe : IDriverProbe
{
private readonly TaskCompletionSource<DriverProbeResult> _tcs =
@@ -175,6 +175,28 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase
db.ConfigEdits.Single().EntityType.ShouldBe("Deployment");
}
/// <summary>
/// lmxopcua#949: a pre-allocated deployment id on the request is the id of the row, the reply and the
/// dispatch — what lets a caller whose ask timed out name (and poll for) the deployment that goes ahead.
/// </summary>
[Fact]
public void StartDeployment_uses_the_preallocated_deployment_id()
{
var dbFactory = NewInMemoryDbFactory();
var coordinator = CreateTestProbe("coord");
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
var id = DeploymentId.NewId();
actor.Tell(new StartDeployment("joe", CorrelationId.NewId(), id));
coordinator.ExpectMsg<DispatchDeployment>(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken)
.DeploymentId.ShouldBe(id);
ExpectMsg<StartDeploymentResult>(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken)
.DeploymentId.ShouldBe(id);
using var db = dbFactory.CreateDbContext();
db.Deployments.Single().DeploymentId.ShouldBe(id.Value);
}
/// <summary>Verifies the full DraftValidator gate (reject on ANY error): a v3 UNS effective-name
/// collision — a UnsTagReference (surfacing a raw Tag under an equipment) and a VirtualTag sharing the
/// same effective leaf name in that equipment's UNS NodeId space — rejects the deploy (422-mapped